58

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.

2
  • 17
    I think it's a lot friendlier to let people type in their phone numbers any way they want. Just strip out non-digits and insist on 10 digits being left after that. Commented Mar 19, 2012 at 19:14
  • 1
    This may be a duplicate, but please link to the previous answers before marking the post. Commented Mar 24, 2015 at 12:23

1 Answer 1

93

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

Sign up to request clarification or add additional context in comments.

12 Comments

The above expression gives success for (000) 000-0000 how can we avoid that?
@HaBo: Why would we want to avoid that?
since it is not a valid phone number.
@HaBo: A regex can't detect valid phone numbers, only validly formatted phone numbers. That said, no U.S. area codes begin with 0 or 1, so if you wanted, you could change the initial [0-9]{3} to [2-9][0-9][0-9].
Yeah I was looking for such thing. So will ^(([2-9]{1}[0-9]{2}) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$ works for (200) 000-0000
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.