Validating Phone Numbers with JavaScript

Solodev
web design by solodev
2 min readOct 3, 2016

--

Forms are only as good as the data they accept and that’s where validation comes in. There are various kinds of validation. In one case, you may just want to make sure the email input was filled out. In another, you want it filled out and to make sure it is valid and contains an @ symbol.

What you don’t see often is telephone number validation because it’s difficult. Not anymore. This tutorial will teach you how to add validation to your phone number input fields using jQuery.

Step 1 — Add the HTML below to where your form will live

<div class="container">
<div class="well">
<div class="row">
<div class="col-md-3">
<label class="control-label">Country:</label>
<div class="country"></div>
</div>
<div class="col-md-3">
<input type="tel" class="tel form-control" pattern="\d*" x-autocompletetype="tel" placeholder="Mobile Phone Number" autofocus>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</div>

Step 2 — Add the CSS below to the main stylesheet of your website

input, div {
font-size: 28px;
font-family: 'Open Sans Condensed', sans-serif;
}
.country {
font-family: 'Open Sans Condensed', sans-serif;
}
.well {
margin-top: 24px;
}
p {
font-size: 22px;
}

Step 3 — Add the JavaScript below to a file called mobileValidate.js

$(document).ready(function() {
jQuery(function($){
var input = $('[type=tel]')
input.mobilePhoneNumber({allowPhoneWithoutPrefix: '+1'});
input.bind('country.mobilePhoneNumber', function(e, country) {
$('.country').text(country || '')
})
});
});

Step 4 — Add the includes below to the web page containing your form

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.caret/0.1/jquery.caret.js"></script>
<script src="https://www.solodev.com/assets/phone/jquery.mobilePhoneNumber.js"></script>
<script src="mobileValidate.js"></script>

Demo on JSFiddle

Download from GitHub

Originally Posted on the Solodev Web Design Blog

Brought to you by the Solodev Team. Solodev is a cloud-based web content management system that empowers users with the freedom to bring amazing web designs to life.

--

--

Solodev
web design by solodev

Solodev helps digital marketers and developers build better websites and digital experiences with free code tutorials at www.solodev.com/blog/