Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regular Expression for International Phone Number

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}$

What needs to be adjusted?

like image 205
Amen Avatar asked Nov 10 '10 18:11

Amen


People also ask

How to validate international phone number using regular expression?

Let's get started: We can easily validate international phone number using regular expression. It works for most of the programming langauges such as .NET, Java, JavaScript, PCRE, Perl, Python, Ruby etc. The numbers should start with a plus sign, followed by the country code and national number.

How to validate phone numbers using JavaScript?

The easiest way to validate phone numbers using Javascript would be to use Regular expressions. However there are different formats of Phone numbers depending on the user's preference. Here are some regular expressions to validate phone numbers

Are there any regex patterns for phone numbers?

If you aren’t careful when building regex patterns, you can waste a lot of time tracking down hard-to-find bugs. That’s why I created this handy collection of regexes that are great for phone numbers. A regular expression to format and validate US (North American) Phone Numbers: 123.456.7890

How do I format International phone numbers in libphonenumber-JS?

The Libphonenumber-js library can format, parse, and validate international telephone numbers using the following scripts: getNumberType – Determines the type of a valid phone number. If possible, categorizes mobile, fixed-rate, toll-free, premium rate, VoIP, or personal numbers.


Video Answer


2 Answers

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, ''));
}
like image 158
BalusC Avatar answered Oct 03 '22 14:10

BalusC


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.

like image 43
Pointy Avatar answered Oct 03 '22 16:10

Pointy