I need to add a regular expression that matches all possible valid E.164 formatted phone numbers.
This regex works fine for for North American phone numbers, but I
The accepted answer doesn't work with numbers without '+' sign. And I did a little math following the Wikipedia metrics,
Country Code : 1 to 3 digits,
maximum : 15,
Actual Phone Number : 12 (upon 15-3) to 14 (15-1) digits
The minimum in this regard is 10. For instance, the dummy US number "+14155552671" is the bare minimum. Breaking it down, +1 is US Country Code and the rest is all 'Area Code' + 'Subscriber Number' which is going to be 10. I couldn't find, in my research, a number less than 7 digits (Sweden) and is valid.
So the regex I had to come up with that works along with '+' sign along with the digits which much reside between 10~15 is as follows:
^\++?[1-9][0-9]\d{6,14}$
And this works well. You can check it out on Regex101.
I think until you have a great set of examples, you are best served by a flexible regex. This one will match a +
followed by 10-14 digits.
^\+?\d{10,14}$
Broken down, this expression means:
^
Match begining of string.
\+?
Optionally match a +
symbol.
\d{10,14}
Match between 10 and 14 digits.
$
Ensure we are at the end of the string.
If you learn that a digit at a particular index must not be 1 or 0, then you can use the [2-9]
at that position, like this:
^\+?\d{6,7}[2-9]\d{3}$
[2-9]
means match any digit from 2 through 9 (don't match 0 or 1.)
Well, I used the accepted answer but it failed for many cases:
For inputs like:
the regex failed.
I finally used
^\+(?:[0-9]?){6,14}[0-9]$
This worked like charm!
This RegEx ^\\+?[0-9]{1,3}[ 1-9]\\d{1,14}$
also works without Invalid regular expression.
This matches only formats like +16174552211
and 16174552211
/\A\+?\d{11}\z/
It is especially useful if you are using Twilio and Ruby on Rails
The accepted answer is good, except an E.164 number can have up to 15 digits. The specification also doesn't indicate a minimum, so I wouldn't necessarily count on 10.
It should be ^\+?[1-9]\d{1,14}$
.
See http://en.wikipedia.org/wiki/E.164