Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate phone number using javascript

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?

like image 972
iJade Avatar asked Aug 22 '13 09:08

iJade


People also ask

How do I validate a phone number?

Mobile Number validation criteria:The first digit should contain numbers between 6 to 9. The rest 9 digit can contain any number between 0 to 9. The mobile number can have 11 digits also by including 0 at the starting. The mobile number can be of 12 digits also by including 91 at the starting.


2 Answers

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;   } } 
like image 135
coolprarun Avatar answered Oct 07 '22 21:10

coolprarun


This regular expression /^(\([0-9]{3}\)\s*|[0-9]{3}\-)[0-9]{3}-[0-9]{4}$/ validates all of the following:

'123-345-3456'; '(078)789-8908'; '(078) 789-8908'; // Note the space 

To break down what's happening:

Regular expression visualization

  1. The group in the beginning validates two ways, either (XXX) or XXX-, with optionally spaces after the closing parenthesis.
  2. The part after the group checks for XXX-XXX
like image 39
Broxzier Avatar answered Oct 07 '22 21:10

Broxzier