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?
This question is related to
javascript
regex
validation
function validatePhone(inputtxt) {_x000D_
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
return phoneno.test(inputtxt)_x000D_
}
_x000D_
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}$/;
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:
(XXX)
or XXX-
, with optionally spaces after the closing parenthesis.XXX-XXX
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/
^(\(?[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.
Here's how I do it.
function validate(phone) {_x000D_
const regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
console.log(regex.test(phone))_x000D_
}_x000D_
_x000D_
validate('1234567890') // true_x000D_
validate(1234567890) // true_x000D_
validate('(078)789-8908') // true_x000D_
validate('123-345-3456') // true
_x000D_
You can use this jquery plugin:
http://digitalbush.com/projects/masked-input-plugin/
Refer to demo tab, phone option.
/^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.
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.
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
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.
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;
}
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.
Source: Stackoverflow.com