In this article I will explain with an example, how to implement US 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="ValidateUSMobileNumber()" />
 
 
Validating US Mobile Number using Regular Expression in JavaScript
When the Submit Button is clicked, the ValidateUSMobileNumber JavaScript function is executed.
Inside the ValidateUSMobileNumber JavaScript function, 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">
    function ValidateUSMobileNumber() {
        var mobileNumber = document.getElementById("txtMobileNumber").value;
        var lblError = document.getElementById("lblError");
        lblError.innerHTML = "";
        var expr = /^(\([0-9]{3}\)|[0-9]{3})[\s\-]?[\0-9]{3}[\s\-]?[0-9]{4}$/;
        if (!expr.test(mobileNumber)) {
            lblError.innerHTML = "Invalid Mobile Number.";
        }
    }
</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; }
</style>
 
 
Screenshot
US Mobile Number validation using JavaScript and Regular Expression
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Demo
 
 
Downloads