Regular expression to validate US phone numbers?

JavascriptRegex

Javascript Problem Overview


> Possible Duplicate:
> A comprehensive regex for phone number validation
> Validate phone number with JavaScript

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.

Javascript Solutions


Solution 1 - Javascript

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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPriyaView Question on Stackoverflow
Solution 1 - JavascriptruakhView Answer on Stackoverflow