3

I need to create a reg expression that validates US phone numbers. The country code is optional as well as parenthesis around the area code. So far I have this

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

it works, however it will allow submissions like

1 555) 555 5555

and

1 (555 555 5555

I need to somehow tell the expression that () are optional but if a user uses one they have to close it off properly as well. How this could be done?

revo
  • 47,783
  • 14
  • 74
  • 117
Optiq
  • 2,835
  • 4
  • 33
  • 68

1 Answers1

4

You have to work with branches:

^1?[-. ]?(?:\((\d{3})\)|(\d{3}))[-. ]?(\d{3})[-. ]?(\d{4})$
            ^^^^^^^^^^^^^^^^^^^

First side of alternation goes with a pair of parentheses and the other side with digits only. This way it doesn't allow unbalanced parentheses to take place.

Live demo

revo
  • 47,783
  • 14
  • 74
  • 117