In this article I will explain with an example, how to implement US Mobile Number validation using Regular Expression (Regex) in jQuery.
HTML Markup
The following HTML Markup consists of an HTML TextBox, SPAN and a Button.
Mobile Number:
<input type="text" id="txtMobileNumber" />
<span id="lblError" class="error">Invalid Mobile Number.</span>
<hr />
<input id="btnSubmit" type="button" value="Submit" />
Validating US Mobile Number using Regular Expression in jQuery
Inside the jQuery document ready event handler, the Submit Button has been assigned a jQuery Click event handler.
When the Submit Button is clicked, the Mobile Number TextBox is referenced and its value is tested using a Regular Expression.
The following conditions must satisfy for a US Mobile Number to be termed as valid.
1. It should be 10 digits long.
2. It may begin with an optional (.
3. After the optional (, it must be 3 digits. If it does not have a (, it must start with 3 digits.
4. It can have an optional ) after first 3 digits.
5. It can have an optional hyphen (-) or empty space after ), if present or after first 3 digits.
6. Then there must be 3 more digits.
7. After second set of 3 digits, it can have another optional hyphen (-) or empty space.
8. Finally, it must end with four digits.
Valid examples: (308)-135-7895, 308-135-7895, 308135-7895, 3081357895, (308) 135 7895, 308 135 7895, 308135 7895
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function () {
var regex = /^(\([0-9]{3}\)|[0-9]{3})[\s\-]?[\0-9]{3}[\s\-]?[0-9]{4}$/;
if (regex.test($("#txtMobileNumber").val())) {
$("#lblError").css("visibility", "hidden");
} else {
$("#lblError").css("visibility", "visible");
}
});
});
</script>
CSS Class
The following CSS class is used for displaying the error message.
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
.error { color: Red; visibility: hidden; }
</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