Swati Awasthi
Swati Awasthi

Reputation: 237

Regular expression in Javascript to validate US phone number

I'm using /^\d{3}\ ?-? ?\d{3}\ ?-? ?\d{4}$/; to validate US phone numbers. Can anyone tell me how to modify this expression to make () optional on the first set of numbers.

For example: it should work for (123)234-2345 , 123-345-4567 , 123 - 345 - 4567 , 123345-6789

Upvotes: 1

Views: 2640

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74098

Area code with or without braces

(?:\(\d{3}\)|\d{3})

optional - with optional spaces around it

(?: *- *)?

3 digits

\d{3}

and 4 digits

\d{4}

and all together now

^(?:\(\d{3}\)|\d{3})(?: *- *)?\d{3}(?: *- *)?\d{4}$

Upvotes: 2

melpomene
melpomene

Reputation: 85887

/^\(?\d{3}\)? ?-? ?\d{3} ?-? ?\d{4}$/

Upvotes: 0

Related Questions