0

I would like to test if the right phone number was enterred in the text field. The phone number should be ddd-ddddddd which means 3digits then must have "-" and then 7 digits. How do I set the regular expression for that ? Thanks :)

4
  • 2
    Exact duplicate of stackoverflow.com/questions/1736686/… Commented Aug 2, 2011 at 20:32
  • I hate sites that require exact formats like that. It's so easy to scan through the digits alone and then add the dashes as necessary. /rant Commented Aug 2, 2011 at 20:34
  • 1
    The format asked for is not the same. Commented Aug 2, 2011 at 20:35
  • I hate sites that require exact formats that only apply to one country. (Unless they make it really clear on the front page that they only deal with residents of that country, and even then - why?) /rant Commented Aug 3, 2011 at 0:07

4 Answers 4

3
/^\d{3}-\d{7}$/.test( phone_number );
Sign up to request clarification or add additional context in comments.

1 Comment

didn't work, can i set it var patt = /^\d{3}-\d{7}$/; and then do patt.test(phonenumber)?
2
var phoneNumber = '123-1234567';
if(phoneNumber.match(/^\d{3}-\d{7}$/))
{
   alert('blah');
}

Comments

1

Exactly as you say it /^\d\d\d-\d\d\d\d\d\d\d$/

8 Comments

There's an extra \d before your hyphen. I'd suggest you use {n} instead, as it's less error-prone.
corrected, thanks, I used this method because it looks very close to how the questioner represented the format himself.
@nobody, your trick didn't work. var phoneNumberPatteern = /^\d\d\d-\d\d\d\d\d\d\d$/; if (phoneNumberPattern.test(phone) == false)
@nobody, I understand what you mean, and it might be a good idea (and maybe your answer will be the accepted one if the questioner understands it best). However, limits in the question should not necessarily lead to limited answers: repeating \d doesn't scale, and if the questioner doesn't know that, doing the same in your answer won't teach him anything.
@AlonB I just tested this code in firefox: var phoneNumberPattern = /^\d\d\d-\d\d\d\d\d\d\d$/; alert( phoneNumberPattern.test('555-7777777') ); result: true
|
0

That's my take:

/^[0-9]{3}\-[0-9]{7}$/

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.