Sunday 16 October 2016

javascript - Regular expression to validate US phone numbers?











I'm trying to write a regular expression to validate US phone number of format

(123)123-1234 -- true
123-123-1234 -- true



every thing else in not valid.



I came up something like



 ^\(?([0-9]{3}\)?[-]([0-9]{3})[-]([0-9]{4})$



But this validates,
123)-123-1234
(123-123-1234



which is NOT RIGHT.


Answer



The easiest way to match both



^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$



and



^[0-9]{3}-[0-9]{3}-[0-9]{4}$


is to use alternation ((...|...)): specify them as two mostly-separate options:



^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$



By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:



^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$


(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...