Validate phone number using javascript
Asked Answered
T

18

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?

That answered 22/8, 2013 at 9:3 Comment(0)
H
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;
  }
}
Husein answered 22/8, 2013 at 9:16 Comment(9)
This will match (123-456 7890 or 123).456-7890, I'm sure that is wanted.Mundane
I cannot Understand what you are upto.. canu explain in brief @M42Husein
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...Mundane
Oh k k now i understood the above solution will accept that input also right ? @M42Husein
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?Lamprey
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.Lamprey
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.phpWarren
this does not handle international phone numbersHydropathy
What happens if the user enters the phone number like this: 5558675309 instead of 555-867-5309?Dubuffet
R
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
Rheinlander answered 22/8, 2013 at 9:7 Comment(1)
It will match (123- 456-7890 or 123)456-7890, I'm not sure that is wanted.Mundane
R
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
Rossie answered 17/1, 2019 at 23:53 Comment(0)
D
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.

Disagreeable answered 28/7, 2016 at 19:38 Comment(0)
L
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.

Lamprey answered 22/8, 2013 at 9:21 Comment(0)
N
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.

Neelon answered 29/1, 2016 at 16:25 Comment(0)
M
1

You can use this jquery plugin:

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

Refer to demo tab, phone option.

Maiden answered 22/8, 2013 at 9:12 Comment(0)
H
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.

Highstepper answered 22/8, 2013 at 9:19 Comment(0)
L
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

Lannie answered 8/10, 2020 at 14:8 Comment(0)
M
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/
Mundane answered 22/8, 2013 at 9:6 Comment(1)
This regex fails for (078)789-8908 too. See my comment at Andy's post.Rheinlander
H
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}$/;
Hyperparathyroidism answered 22/8, 2013 at 9:6 Comment(4)
This one fails for (078)789-8908 because of the space. You should add a ? there.Rheinlander
There isn't a space in the example in the question, but I'll amend my answer.Hyperparathyroidism
Yours validated the ones with spaces, and not the ones without.Rheinlander
Fixed to account for an optional space.Hyperparathyroidism
S
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;
}
Shavonda answered 16/4, 2017 at 4:6 Comment(0)
S
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.

Soneson answered 22/1, 2019 at 22:3 Comment(0)
I
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;
  }
}
Irrationality answered 23/6, 2021 at 3:1 Comment(1)
Please add some description to explain your code.Liaison
E
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);
}
Exudate answered 24/12, 2022 at 17:35 Comment(0)
F
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))
Flanders answered 11/3, 2023 at 20:3 Comment(0)
D
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
Delaware answered 24/5, 2024 at 12:21 Comment(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.Mellifluous
T
-1

function validatePhone(inputtxt) {
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  return phoneno.test(inputtxt)
}
Tonitonia answered 7/3, 2017 at 1:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.