JS Input Validation – III (Phone Number)

To validate phone number using JavaScript is an important point while validating an HTML form. At first, we validate a phone number of 10 digits with no comma, no spaces, no punctuation and there will be no + sign in front the number. Simply the validation will remove all non-digits and permit only phone numbers with 10 digits.

Explanation

The JS code mentioned below is better understood, if we have analyzed the following regular expression for phone number validation.

Regular Expression Pattern:
/^\d{10}$/

The complete code is given below.

HTML embedded JS code to validate a date:

<html>
<head>
<title>JavaScript email validation</title>
<script language="javascript">
function validatePhone(text)
{
var phoneno = /^\d{10}$/;

if((text.value.match(phoneno))
{
document.frm.txt.focus();
return true;
}
else
{
alert("message");
return false;
}
}
</script>
</head>
<body onload='document.frm.txt.focus()'>
<h2>Input an email and Submit</h2>
<form name="frm" action="test.html" onSubmit="return validatePhone(document.frm.txt)">
<input type="text" name="txt"/>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

 

Note: We must implement the web page named “test.html” as mentioned in the previous code.

To valid a phone number like

XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX

we should use the following pattern.

var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;