Validate Phone Numbers Using jQuery and PHP: 3 Effective Ways

Learn how to validate phone numbers using jQuery and PHP in 5 simple steps. Enhance user experience and ensure data accuracy with real-time validation examples.
Validating phone numbers is a critical feature in web applications. Whether you’re creating a registration form or a checkout page, ensuring that users input a correct and valid phone number enhances both the user experience and data accuracy. In this guide, we’ll cover how to validate phone numbers using jQuery and PHP, offering practical examples and best practices. Let’s dive into phone number validation and explore examples such as 10-digit mobile number validation using regex.

Why Phone Number Validation Matters

Enhancing User Experience

Real-time phone number validation provides immediate feedback to users, reducing errors and frustration. When a user knows they’ve entered the wrong format instantly, it makes the form submission process smoother and more user-friendly.

Ensuring Data Accuracy

Having accurate phone numbers is crucial for communication and customer data integrity. A robust validation system ensures you’re collecting correct and usable data at the point of entry, preventing errors or issues later on.

Example 1: Validate 10-Digit Mobile Number Using Regex

Let’s begin with a basic example of validating a 10-digit mobile number using regular expressions in jQuery. This method allows you to check if the user has entered the correct number of digits.


<html>
    <head>
        <title>Allow Only 10-Digit Contact Number Using Regex - customsite</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    <body>
    <form>
        <h1>Allow Only 10-Digit Contact Number Using Regex - customsite</h1>
        <div>
            <label>Contact Number: </label>
            <input type="text" name="contact_number" placeholder="Contact Number" minlength="10" maxlength="10" required>
            <br>
            <label>Contact Number: </label>
            <input type="text" name="contact_number" placeholder="Contact Number" pattern="[1-9]{1}[0-9]{9}" required><br>
            <button type="submit">Submit</button>
        </div>
    </form>
    </body>
    </html>

Example 2: Regular Expression for 10-Digit Contact Number Validation

In this example, we will use jQuery to validate a 10-digit contact number. The code below uses a regular expression to ensure that only valid phone numbers are accepted.


 <html>
    <body>
        Contact Number: <input type='text' id='contact_num'/>
        <span id="status_msg"></span>
    </body>
    </html>
    <script>
    $(document).ready(function() {
        $('#contact_num').blur(function(e) {
            if (checkPhoneNumber('contact_num')) {
                $('#status_msg').html('Valid');
                $('#status_msg').css('color', 'green');
            } else {
                $('#status_msg').html('Invalid');
                $('#status_msg').css('color', 'red');
            }
        });
    });
    function checkPhoneNumber(contact_num) {
        var numValue = document.getElementById(contact_num).value;
        var pattern = /^(+d{1,2}s)?(?d{3})?[s.-]d{3}[s.-]d{4}$/;
        if (pattern.test(numValue)) {
            return true;
        } else {
            return false;
        }
    }
    </script>             

This code checks the input and provides instant feedback, improving the user experience.

Example 3: Validate Non-US Numbers

If you’re dealing with international users, you might want to ensure that your system can differentiate between US and non-US phone numbers. The following example focuses on validating US phone numbers only.


  <html>
  <body>
          Phone Number: <input type='text' id='phone_input'/>
          <span id="validation_result"></span>
  </body>
  </html>
  <script>
  $(document).ready(function() {
      $('#phone_input').blur(function(e) {
          if (validateUSPhone('phone_input')) {
              $('#validation_result').html('Valid US Number');
              $('#validation_result').css('color', 'green');
          } else {
              $('#validation_result').html('Invalid');
              $('#validation_result').css('color', 'red');
          }
      });
  });
  function validateUSPhone(phone_input) {
      var phoneValue = document.getElementById(phone_input).value;
      var usPattern = /^(+0?1s)?(?d{3})?[s.-]d{3}[s.-]d{4}$/;
      if (usPattern.test(phoneValue)) {
          return true;
      } else {
          return false;
      }
  }
  </script>                 

Common Formats that Match the Above Validation

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

For more detail you can write jquery Documentation

Summary

Phone number validation is crucial in modern web applications to ensure data integrity and enhanced user experience. With the use of regular expressions and jQuery, you can create dynamic and real-time validation that provides immediate feedback to your users. Whether you’re handling 10-digit numbers, US-based numbers, or international numbers, these practical examples will help you implement robust validation systems in your projects.

You may also find interesting:

Laravel Create Zip File and Download Example: A Comprehensive Guide

Post a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *