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?

1

1 Answer 1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.