Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  132] [ 6]  / answers: 1 / hits: 198056  / 11 Years ago, thu, august 22, 2013, 12:00:00

I'm trying to validate phone number such as 123-345-3456 and (078)789-8908 using JavaScript.
Here is my code



function ValidateUSPhoneNumber(phoneNumber) {
var regExp = /^(([0-9]{3}) |[0-9]{3}-)[0-9]{3}-[0-9]{4}/;
var phone = phoneNumber.match(regExp);
if (phone) {
alert('yes');
return true;
}
alert('no');
return false;
}


I'm testing the function using ValidateUSPhoneNumber('123-345-34567') which has 5 digits before the last hyphen which is invalid as per regex. But the function returns true.
Can any one explain why?


More From » regex

 Answers
4

JavaScript to validate the phone number:





function phonenumber(inputtxt) {
var phoneno = /^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(inputtxt.value.match(phoneno)) {
return true;
}
else {
alert(message);
return false;
}
}





The above script matches:



XXX-XXX-XXXX

XXX.XXX.XXXX

XXX XXX XXXX



If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX

+XX XXXX XXXX
use the following code:



function phonenumber(inputtxt) {
var phoneno = /^+?([0-9]{2}))?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(inputtxt.value.match(phoneno)) {
return true;
}
else {
alert(message);
return false;
}
}

[#76225] Tuesday, August 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
vaughns

Total Points: 20
Total Questions: 112
Total Answers: 112

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;