admin管理员组

文章数量:1135889

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?

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?

Share Improve this question edited Feb 26, 2018 at 6:13 GG. 21.8k14 gold badges90 silver badges132 bronze badges asked Aug 22, 2013 at 9:03 iJadeiJade 23.8k58 gold badges159 silver badges249 bronze badges 0
Add a comment  | 

17 Answers 17

Reset to default 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;
  }
}

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:

  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

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

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.

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.

^(\(?[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.

You can use this jquery plugin:

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

Refer to demo tab, phone option.

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.

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/

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

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

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;
}
/^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.

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

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

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))

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

本文标签: regexValidate phone number using javascriptStack Overflow