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 :)
-
2Exact duplicate of stackoverflow.com/questions/1736686/…Lance– Lance2011-08-02 20:32:24 +00:00Commented 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. /rantChris Gregg– Chris Gregg2011-08-02 20:34:53 +00:00Commented Aug 2, 2011 at 20:34
-
1The format asked for is not the same.Alex Turpin– Alex Turpin2011-08-02 20:35:41 +00:00Commented 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?) /rantnnnnnn– nnnnnn2011-08-03 00:07:12 +00:00Commented Aug 3, 2011 at 0:07
Add a comment
|
4 Answers
/^\d{3}-\d{7}$/.test( phone_number );
1 Comment
Alon B
didn't work, can i set it var patt = /^\d{3}-\d{7}$/; and then do patt.test(phonenumber)?
Exactly as you say it /^\d\d\d-\d\d\d\d\d\d\d$/
8 Comments
Frédéric Hamidi
There's an extra
\d before your hyphen. I'd suggest you use {n} instead, as it's less error-prone.nobody
corrected, thanks, I used this method because it looks very close to how the questioner represented the format himself.
Alon B
@nobody, your trick didn't work. var phoneNumberPatteern = /^\d\d\d-\d\d\d\d\d\d\d$/; if (phoneNumberPattern.test(phone) == false)
Frédéric Hamidi
@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.nobody
@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 |