Javascript Regular Expression for International Phone Number

前端 未结 4 1507
有刺的猬
有刺的猬 2021-02-06 17:05

The following regular expression isn\'t working for international phone numbers that can allow up to 15 digits:

^[a-zA-Z0-9-().\\s]{10,15}$

W

相关标签:
4条回答
  • 2021-02-06 17:46

    You may find the following regex more useful, it basically first strips all valid special characters which an international phone number can contain (spaces, parens, +, -, ., ext) and then counts if there are at least 7 digits (minimum length for a valid local number).

    function isValidPhonenumber(value) {
        return (/^\d{7,}$/).test(value.replace(/[\s()+\-\.]|ext/gi, ''));
    }
    
    0 讨论(0)
  • 2021-02-06 18:06

    Try adding a backslash:

    var unrealisticPhoneNumberRegex = /^[a-zA-Z0-9\-().\s]{10,15}$/;
    

    Now it's still not very useful because you allow an arbitrary number of punctuation characters too. Really, validating a phone number like this — especially if you want it to really work for all possible international phone numbers — is probably a hopeless task. I suggest you go with what @BalusC suggests.

    0 讨论(0)
  • 2021-02-06 18:06

    and then counts if there are at least 7 digits (minimum length for a valid local number).

    The shortest local numbers anywhere in the world are only two or three digits long.

    There are many countries without area codes.

    There are several well-known places with a 3 digit country code and 4 digit local numbers.

    It may be prudent to drop your limit to 6 or 5; just in case.

    0 讨论(0)
  • 2021-02-06 18:08

    See A comprehensive regex for phone number validation and Is there a standard for storing normalized phone numbers in a database?

    0 讨论(0)
提交回复
热议问题