I want to validate a 10 digit USA style phone number using a Regular Expression in Javascript and then submit it to the PHP server via the url. It will be a simple text box in a form for typing in the number and a button to submit.
For example, after validation, the url might be:
thisdomainname.com/resultspage.php?phonenumber=4392931234
I know how regular expressions work but am confused by more complex ones. I have searched stackoverflow and the internet for a solution and found several but none that fits what I need exactly and/or works when I run it.
I need it to omit all non numeric characters (such as parens, dashes and periods), and also omit the extra leading "1" that is optional in USA 10 digit phone numbers.
It should allow (validate as correct) the following formats:
1-(805) xxx-xxxx
215.xxx.xxxx
But reject as invalid:
805 931 42
805 931 42ab
105 931 4288
Ideally it would allow phone numbers according to the "North American Numbering Plan," which has the following rules:
"Area codes start with a number from 2–9, followed by 0–8, and then any third digit. The second group of three digits, known as the central office or exchange code, starts with a number from 2–9, followed by any two digits. The final four digits, known as the station code, have no restrictions."
I found a regex to implement this below, but I can't get it to work with the optional leading "1" digit.
^\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$
Like I say, I have found many solutions addressing this problem in general, but none that will work with all the situations I've outlined above.
Thanks in advance.