Phone Number Validation Using jQuery

Validation of a phone number is required when we validate an HTML form. In this tutorial we will see how to validate a phone number using jQuery.

Now a day phone number became a mandatory field in registration form and we must validate it before submit. Firstly we check for non empty and for 10 digit numeric value.

On validation failed, we append specific error message to main div so that user can get what is wrong while submitting the form.

We have used span having class name error to display form error in it using jQuery append() method. jQuery.css() method is used to display error colour which set style properties for used span element.

Let us see how phone number validation is done using jQuery.

Show and Hide Password Field with jQuery and JavaScript
jQuery Validation for File Input Type

Table of Contents

HTML

<div class="container-fun">
<h1>Phone Number Validation Using jQuery</h1>
<form method="POST" id="phone_submit">
<input type="text" name="phone" id="phone" class="input">
<input type="submit" name="submit" value="Submit" class="btn" onclick="return phoneValidate();">
</form>
</div>

jQuery

<script>
function phoneValidate(){
var mobile= jQuery("#phone").val();
var pattern = /^\d{10}$/;

if (pattern.test(mobile)) {
jQuery(".error").html('');
return true;
} else{
jQuery(".error").html('');
jQuery(".container-fun").append("<span class='error'>Please put 10 digit valid mobile number</span>");
jQuery(".error").css('color','red');
return false;
}
}
</script>

CSS

.container-fun
{
margin: 100px auto;
text-align: center;
width:483px;
height:150px;
}
h1
{
margin: 50px auto;
text-align: center;
color: green;
font-size: 24px;
}
.btn
{
background-color: #2d6586;
color: #fff;
padding: 7px 12px 12px 19px;
display: inline-block;
font-family: 'Montserrat';
font-size: 18px;
letter-spacing: 2px;
cursor: pointer;
font-weight: bold;
border: none;
}
.input
{
width: 286px;
padding: 10px 13px 11px 21px;
display: inline-block;
font-family: 'Montserrat';
font-size: 12px;
letter-spacing: 2px;
cursor: pointer;
}
#phone_submit
{
margin: 50px auto;
text-align: center;
}

So with above given script you can understand how to implement Phone number validation using jQuery.

If you have any query regarding this article feel free to comment.

Leave a Comment