Validate phone number using javascript

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;
  }
}

Leave a Comment