Howdy
I’ve been searching for a decent phone number regular expression validation and it turns out a lot harder to dig one up than I expected. I’ve found plenty, but it turns out that most of them appear on the surface to be fine, but in reality they don’t actually work, like this one:
//Example, try this out for yourself
var phoneRegEx = /\\(?\\d{3}\\)?[-\\/\\.\\s]?\\d{3}[-\\/\\.\\s]?/;
var string = 'this does not belong here 01 2345 6789';
alert(string.match(phoneRegex));
As you can see, this phone validation routine is no good. So, I decided to come up with my own expression that could, as best as possible handle phone number in Australian format, firstly, but in formats from international numbers wherever possible too. Here’s the kind of phone formats I am thinking of:
Standard Telephone numbers
+61 1 2345 6789
+61 01 2345 6789 (zero entered is not required but enterd by user anyway)
01 2345 6789
01-2345-6789
(01) 2345 6789
(01) 2345-6789
1234 5678
1234-5678
12345678
Mobile Numbers
0123 456 789
0123456789
International Phone Numbers
US Format - +1 (012) 456 7890
US Virgin Islands (four digit international code) +1-340 123 4567
You get the idea. So here’s the expression I’ve come up with…
var phoneRegEx = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/;
It’s far from perfect but it might be a step in the right direction. I’m hoping someone here might be able to provide some input to improve upon this, or even simplify it to make it work better.
One of the main problems with it is that it will allow a number through with more than 8 or 10 digits, which is not a valid phone number, at least that I am aware of. Something like 0123456789876543210 would get through when it shouldn’t.