user3101582
user3101582

Reputation: 57

validate a 10 digit USA style phone number using a Regular Expression in Javascript

I want to validate a 10 digit USA style phone number using a Regular Expression in Javascript

It should allow (validate as correct) the following formats:

xxx-xxx-xxxx

215-121-1247

It should reject as invalid:

8059311142
805 931 42ab
105 931 4288

I found a regex to implement this below, but I can't get it to work.

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

please help me on this

Upvotes: 0

Views: 749

Answers (1)

sshashank124
sshashank124

Reputation: 32207

You can very simply do it as:

^\d{3}-\d{3}-\d{4}$

Demo: http://regex101.com/r/jV1hP3

To understand what your regex is doing, check this link

Upvotes: 1

Related Questions