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.

The HTML

<html>
<head>
<title>Phone validation</title>
</head>
<body>
<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>
</form>
<p>
<p>
Checkout my <a href="https://anjandutta.com">blog</a> for more tutorial.
</body>
</html>

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