How To Validate Phone Number In Jquery

In this blog post, we will discuss how to validate phone numbers using jQuery. Validating user inputs, such as phone numbers, is crucial for ensuring data integrity and user experience. A valid phone number helps prevent errors and issues when trying to reach a user or customer.

Approach

We will use jQuery to perform the phone number validation. jQuery is a popular JavaScript library that simplifies HTML document traversing, event handling, and animations. It works on many platforms and is easy to use.

To get started, you need to include the jQuery library in your HTML file. You can download it from the jQuery website or use a CDN link like the one shown below:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Phone Number Validation Using jQuery

We will use a simple regular expression to validate the phone number. A regular expression is a pattern that specifies a set of strings. In our case, it will define the valid format for phone numbers. We will use the following regular expression:

/^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/

This regular expression allows for various phone number formats like:

  • 123-456-7890
  • (123) 456-7890
  • 123.456.7890
  • 1234567890
  • +1 (123) 456-7890

Now, let’s create a simple HTML form with an input field for the phone number:

<form id="phoneForm">
    <label for="phoneNumber">Phone Number:</label>
    <input type="text" id="phoneNumber" name="phoneNumber">
    <button type="submit">Submit</button>
</form>
<div id="result"></div>

Next, we will write the jQuery code to validate the phone number upon form submission:

$(document).ready(function () {
    $("#phoneForm").submit(function (event) {
        event.preventDefault();

        var phoneNumber = $("#phoneNumber").val();
        var regex = /^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;

        if (regex.test(phoneNumber)) {
            $("#result").html("<strong>Valid phone number!</strong>");
        } else {
            $("#result").html("<strong>Invalid phone number. Please check the format.</strong>");
        }
    });
});

In the above code, we first use event.preventDefault() to prevent the default form submission behavior. Then, we get the value of the input field and check it against our regular expression using the test() method. If the phone number matches the regular expression, we display a “Valid phone number!” message. Otherwise, we display an error message asking the user to check the format.

Conclusion

In this blog post, we demonstrated how to validate phone numbers using jQuery and regular expressions. This technique can help ensure that the user inputs a valid phone number, improving data integrity and user experience. Remember to always validate user inputs on both the client and server sides for maximum security and reliability.