Validate phone number using javascript
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
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 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.
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:
- The group in the beginning validates two ways, either
(XXX)
orXXX-
, with optionally spaces after the closing parenthesis. - The part after the group checks for
XXX-XXX