user2855405
user2855405

Reputation: 515

How to validate a phone number in this format

So in my check phone number function, I have: the variable pn represents the textfield where the client inputs the phone number.

The desired format is: 000-0000 (obviously not only zeroes, but any digit 0-9).

How can I use regex to validate that it is in the desired format, and give an alert if it isn't? This is what i have

var pn = document.getElementById('ph').value;
//var vd = pn.search?

//if(not valid, alert("Not a valid number!");

Upvotes: 1

Views: 618

Answers (1)

anubhava
anubhava

Reputation: 785971

The desired format is: 000-0000

Then following regex should work:

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

TEST:

re = /^\d{3}-\d{4}$/;

re.test('123-4567'); // true
re.test('123-45678'); // false

Upvotes: 3

Related Questions