开发者

Validates as a phone number

I am trying to validate a string as a phone number (digits and certain special characters). I used a existing code snippet from here: http://snippets.dzone.com/posts/show/597 which seems to be correct. But everytime string.match(format) returns null, which causes to show the error message.

var format = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
var string = jQuery(".validate_phone").val();
if (string.match(format) != true) {
  // some error message
}

I checked already, string is filled which the expected value.

The following values should match:

339-4248

339-42-48

339 42 48

339 4248

3394248

(095) 3394248

(095)3394248

+7 (095) 3394248

+7 (095)3394248

+7(095) 3394248

+7(095)3394248

Everything else sh开发者_如何学Could show the error message.

What is wrong with this code? Thanks in advance!

Update: Here is a test case http://labuschin.com/material/phone


A friend over at Facebook helped me out successfully:

var format = /(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}/;  
var nr= prompt("Phone number", "");    
if (nr.match(format) == null) {
  alert ("incorrect");  
} else {  
  alert ("correct");  
} 

Changed if-clause and and removed the ^ at the beginning and the $ at the end. Works here: http://labuschin.com/material/phone


A valid regex for that would be: (\+\d\s*)?(\(\s*\d{3}\s*\)\s*)?\d{3}([- ]?\d{2}){2}.

However, match() returns null on non-matches and an array of captured values on matches - it will never return true. You are probably more interested in search() which returns the match position or -1 if the regex didn't match. E.g.:

var format = /^(\+\d\s*)?(\(\s*\d{3}\s*\)\s*)?\d{3}([- ]?\d{2}){2}$/;
var string = jQuery(".validate_phone").val();
if (string.search(format) == -1) {
  // some error message
}


Maybe... you should not use "string" as var name.

var format = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
var nr= prompt("Phone number", "");
if (!nr.match(format)) {
alert ("incorrect");
} else {
alert ("correct");
} 

works for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜