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?

0

18 Answers 18

57

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;
  }
}
9
  • This will match (123-456 7890 or 123).456-7890, I'm sure that is wanted.
    – Toto
    Commented Aug 22, 2013 at 9:26
  • I cannot Understand what you are upto.. canu explain in brief @M42
    – coolprarun
    Commented Aug 22, 2013 at 9: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
    Commented Aug 22, 2013 at 9:34
  • Oh k k now i understood the above solution will accept that input also right ? @M42
    – coolprarun
    Commented Aug 22, 2013 at 9:39
  • 1
    Could you please cite that your answer was from here (unless it's your own post there or something): w3resource.com/javascript/form/phone-no-validation.php Commented Apr 10, 2014 at 10:05
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
1
  • 1
    It will match (123- 456-7890 or 123)456-7890, I'm not sure that is wanted.
    – Toto
    Commented Aug 22, 2013 at 9:28
7

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

0
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.

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.

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.

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.

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

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/
1
  • This regex fails for (078)789-8908 too. See my comment at Andy's post.
    – Broxzier
    Commented Aug 22, 2013 at 9:17
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}$/;
4
  • 1
    This one fails for (078)789-8908 because of the space. You should add a ? there.
    – Broxzier
    Commented Aug 22, 2013 at 9:16
  • There isn't a space in the example in the question, but I'll amend my answer.
    – Andy
    Commented Aug 22, 2013 at 9:20
  • Yours validated the ones with spaces, and not the ones without.
    – Broxzier
    Commented Aug 22, 2013 at 9:21
  • Fixed to account for an optional space.
    – Andy
    Commented Aug 22, 2013 at 9:24
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;
  }
}

1
  • Please add some description to explain your code.
    – a.ak
    Commented Jun 23, 2021 at 5:16
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);
}
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))
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;
  }
}

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

0782 607 5656 enter link description here

Facebook

enter code here
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented May 24 at 21:19
-1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.