Home » Javascript » How do I set a regexp with optional “(” and “)” that requires both when used?

How do I set a regexp with optional “(” and “)” that requires both when used?

Posted by: admin October 18, 2018 Leave a comment

Questions:

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?

Answers: