41

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?

GG.
  • 21,083
  • 14
  • 84
  • 130
iJade
  • 23,144
  • 56
  • 154
  • 243

17 Answers17

56

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;
  }
}
ide
  • 19,942
  • 5
  • 64
  • 106
coolprarun
  • 1,153
  • 2
  • 15
  • 22
  • This will match `(123-456 7890` or `123).456-7890`, I'm sure that is wanted. – Toto Aug 22 '13 at 09:26
  • I cannot Understand what you are upto.. canu explain in brief @M42 – coolprarun Aug 22 '13 at 09:30
  • Just try with example I've given. The parenthesis are optional in your regexp, so you can have one but not the second. Also if there is is an hyphen as first separator, you accept dot as second separator... – Toto Aug 22 '13 at 09:34
  • Oh k k now i understood the above solution will accept that input also right ? @M42 – coolprarun Aug 22 '13 at 09:39
  • I think it's worth asking: are we trying to find any string that looks like a phone number in a document? Or are we trying to validate user input? – Secesh Aug 22 '13 at 09:42
  • because if we're validating user input, it'd be a heck of a lot easier to strip out the special characters and say: is it a 10-digit number? and if so, maybe do some logic on the composition of that number. Then reformat it as desired. That'd be a heck of a lot easier than trying to craft the perfect regex. – Secesh Aug 22 '13 at 09:44
  • 1
    Could you please cite that your answer was from here (unless it's your own post there or something): http://www.w3resource.com/javascript/form/phone-no-validation.php – Qantas 94 Heavy Apr 10 '14 at 10:05
  • this does not handle international phone numbers – kpg Mar 05 '15 at 15:27
  • What happens if the user enters the phone number like this: 5558675309 instead of 555-867-5309? – Kenny Johnson Sep 18 '15 at 21:23
35

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
Broxzier
  • 2,909
  • 17
  • 36
6

Here's how I do it.

function validate(phone) {
  const regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  console.log(regex.test(phone))
}

validate('1234567890')     // true
validate(1234567890)       // true
validate('(078)789-8908')  // true
validate('123-345-3456')   // true
Muhammad Ovi
  • 1,053
  • 14
  • 26
4

This is by far the easiest way I have found to use javascript regex to check phone number format. this particular example checks if it is a 10 digit number.

<input name="phone" pattern="^\d{10}$" type="text" size="50">

The input field gets flagged when submit button is clicked if the pattern doesn't match the value, no other css or js required.

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Mike Volmar
  • 1,927
  • 1
  • 22
  • 31
2

can anyone explain why

because your regular expression does match the input. It's just that the input also includes the extra characters. You included '^' to signify the beginning of line, but (as Andy said) you should include '$' to signify the end of line.

If you start your regex with '^' and end it with '$', then it will only match lines that only match your regex.

By starting your regex with '^' and not ending it with '$', you match lines that start with a sequence matching your regex, but lines can have anything else trailing the matching sequence.

Secesh
  • 385
  • 2
  • 9
2

^(\(?[0-9]{3}\)?)((\s|\-){1})?[0-9]{3}((\s|\-){1})?[0-9]{4}$

Assuming you are validating US phone numbers, this will do the trick.

First, we allow 0 or 1 open parentheses to start \(?

Then, we allow 3 consecutive digits between 0-9 [0-9]{3}

After, we repeat the first step and allow 0 or 1 closing parentheses \)?

For the second grouping, we start by allowing a space or a hyphen 0 or 1 times ((\s|\-){1})?

This is repeated between the second and third grouping of numbers, and we check for 3 consecutive digits then four consecutive digits to end it. For US phone numbers I think this covers the bases for a lot of different ways that people might format the number, but is restrictive enough that they can't pass an unreasonable string.

1

You can use this jquery plugin:

http://digitalbush.com/projects/masked-input-plugin/

Refer to demo tab, phone option.

Sheetal
  • 1,368
  • 1
  • 9
  • 15
1

Can any one explain why??

This happening because your regular expression doesn't end with any anchor meta-character such as the end of line $ or a word boundary \b.

So when you ask the regex engine whether 123-345-34567 is valid phone number it will try to find a match within this string, so it matches 123- with this part (\([0-9]{3}\) |[0-9]{3}-) then it matches 345- with this part [0-9]{3}- then it matches 3456 with this part [0-9]{4}.

Now the engine finds that it has walked the entire regex and found a string inside your input that matches the regex although a character was left - the number 7- in the input string, so it stops and returns success because it found a sub-string that matches.

If you had included $ or \b at the end of your regex, the engine walks the same way as before then it tries to match $ or \b but finds the last number - the 7 - and it is not a word boundary \b nor a an end of line $ so it stops and fails to find a match.

Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
1

In JavaScript, the below regular expression can be used for a phone number :

^((\+1)?[\s-]?)?\(?[1-9]\d\d\)?[\s-]?[1-9]\d\d[\s-]?\d\d\d\d

e.g; 9999875099 , 8750999912 etc.

Reference : https://techsolutions.filebizz.com/2020/08/regular-expression-for-phone-number-in.html

General Grievance
  • 4,555
  • 31
  • 31
  • 45
0

Add a word boundary \b at the end of the regex:

/^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/

if the space after ) is optional:

/^(\([0-9]{3}\)\s*|[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/
Toto
  • 89,455
  • 62
  • 89
  • 125
0

Add a $ to the end of the regex to signify the end of the pattern:

var regExp = /^(\([0-9]{3}\)\s?|[0-9]{3}-)[0-9]{3}-[0-9]{4}$/;
Andy
  • 61,948
  • 13
  • 68
  • 95
0

If you using on input tag than this code will help you. I write this code by myself and I think this is very good way to use in input. but you can change it using your format. It will help user to correct their format on input tag.

$("#phone").on('input', function() {  //this is use for every time input change.
        var inputValue = getInputValue(); //get value from input and make it usefull number
        var length = inputValue.length; //get lenth of input

        if (inputValue < 1000)
        {
            inputValue = '1('+inputValue;
        }else if (inputValue < 1000000) 
        {
            inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, length);
        }else if (inputValue < 10000000000) 
        {
            inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, length);
        }else
        {
            inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, 10);
        }       
        $("#phone").val(inputValue); //correct value entered to your input.
        inputValue = getInputValue();//get value again, becuase it changed, this one using for changing color of input border
       if ((inputValue > 2000000000) && (inputValue < 9999999999))
      {
          $("#phone").css("border","black solid 1px");//if it is valid phone number than border will be black.
      }else
      {
          $("#phone").css("border","red solid 1px");//if it is invalid phone number than border will be red.
      }
  });

    function getInputValue() {
         var inputValue = $("#phone").val().replace(/\D/g,'');  //remove all non numeric character
        if (inputValue.charAt(0) == 1) // if first character is 1 than remove it.
        {
            var inputValue = inputValue.substring(1, inputValue.length);
        }
        return inputValue;
}
0
/^1?\s?(\([0-9]{3}\)[- ]?|[0-9]{3}[- ]?)[0-9]{3}[- ]?[0-9]{4}$/

This will validate all US style numbers, with or without the 1, and with or without parenthesis on area code(but if used, used properly. I.E. (902-455-4555 will not work since there is no closing parenthesis. it also allows for either - or a space between sets if wanted.) It will work for the examples provided by op.

0

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

Return true if the passed string looks like a valid US phone number.

function isValidPhoneNumber(phoneNumber) {
  const regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;
  return regex.test(phoneNumber);
}
ravina vala
  • 119
  • 4
0

NOTE: The pattern is not enclosed in quotes

const tel = '9898989898';

const my_regex_pattern = /^([+]\d{2})?\d{10}/;

console.log(my_regex_pattern.test(tel))
markalex
  • 8,623
  • 2
  • 7
  • 32
-1

function validatePhone(inputtxt) {
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  return phoneno.test(inputtxt)
}
akiva
  • 171
  • 2
  • 11