In this article I will explain with an example, how to implement Indian Mobile Number validation using Regular Expression (Regex) in JavaScript.
HTML Markup
The following HTML Markup consists of an HTML TextBox, SPAN and a Button.
The Button has been assigned a JavaScript OnClick event handler.
Mobile Number:
<input type="text" id="txtMobileNumber" />
<span id="lblError" class="error"></span>
<hr/>
<input type="button" value="Submit" onclick="ValidateMobileNumber()" />
Validating Mobile Number using Regular Expression in JavaScript
When the Submit Button is clicked, the ValidateMobileNumber JavaScript function is executed.
Inside the ValidateMobileNumber JavaScript function, the Mobile Number TextBox is referenced and its value is tested using a Regular Expression.
The following conditions must satisfy for a Mobile Number to be termed as valid.
1. It should be 10 digits long.
2. The first digit should be a number. 6 to 9.
3. The rest 9 digits should be any number. 0 to 9.
4. It can have 11 digits including 0 at the starting.
5. It can have 12 digits including 91 at the starting.
Examples: 9876543210, 09876543210, 919876543210
<script type="text/javascript">
function ValidateMobileNumber() {
var mobileNumber = document.getElementById("txtMobileNumber").value;
var lblError = document.getElementById("lblError");
lblError.innerHTML = "";
var expr = /^(0|91)?[6-9][0-9]{9}$/;
if (!expr.test(mobileNumber)) {
lblError.innerHTML = "Invalid Mobile Number.";
}
}
</script>
CSS Class
The following CSS class is used.
error – It will apply RED color to the error message.
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
.error { color: Red; }
</style>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads