Anjan Dutta

How to do phone number validation in JavaScript

How to do phone number validation in JavaScript

We can validate a phone number in javascript using the RegEx pattern match.

This is the best way of doing phone validation in javascript.

The best part is, we can customize the RegEx as per our requirement to support different country specific rules.

The code supports below formats:

123 456 7890 123.456.7890 123-456-7890 (123) 456-7890

See the working code below.


<title>Phone validation</title>
<form name="myForm" novalidate onsubmit="return false;">
<label for="p_input">Enter Phone Number</label>
<input type="email" name="p_input" id="p_input" required>
<button type="submit" onclick="validatePhone(document.getElementById('p_input').value)">Submit</button>
Checkout my <a href="">blog</a> for more tutorial.

In above code, the <form> tag has these attributes novalidate onsubmit="return false;". The novalidate disables default HTML form validation and the onsubmit="return false;" stops the form submit event and lets the validation function run.

The JavaScript

function validatePhone(phone) {
const phoneValidatorRegEx = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/
let result = phoneValidatorRegEx.test(String(phone).toLowerCase());
let isValid = result==true?"a valid ": "an invalid ";
console.log(phone + " is " + isValid + "number");