Objectives and outcomes

In this tutorial we are going to learn about validating various formats of phone number in javascript. In javascript we validate phone number by using Regular expression. Example for the same is shown below :



HTML code:

<html>
<body>
<form name="form1" onSubmit="return(form_valid());" method="post">
phone no.&nbsp;<input type="text" name="phno"><br/><br/>
<input type="submit" value="submit">
</form>
</body>
</html>





Validating phone number of format ##########

<script>
function form_valid()  
{  
var phoneno = /^\d{10}$/;  
if(document.forms["form1"]["phno"].value.match(phoneno))  
{  
return true;  
}  
else  
{  
alert("Not a valid Phone Number");  
return false;  
}  
}  
</script>


Validating a phone number of format 232-456-8765, 232.456.8765 or 232 456 8765

<script>
function form_valid()
{
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(document.forms["form1"]["phno"].value.match(phoneno))
{
return true;<br/>
}
else
{
alert("Not a valid Phone Number");
return false;
}
}
</script>


In the first we have only checked for the 10 digits only in which d stand for digit and {10} is for the length of the input. In the second case we first checked for digit with length=3 and then for symbols like - , . , '' and again repeating the same process and in the last checking for digit with lenght=4.