Martin Labuschin
Martin Labuschin

Reputation: 516

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 should show the error message.

What is wrong with this code? Thanks in advance!

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

Upvotes: 1

Views: 448

Answers (3)

Martin Labuschin
Martin Labuschin

Reputation: 516

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

Upvotes: 3

Orange
Orange

Reputation: 1

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.

Upvotes: 0

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

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
}

Upvotes: 0

Related Questions