Add Phone Number Validation Using Regex jQuery

In this article, we will learn how to add phone number validation using regex jQuery.

There are two ways to add phone number validation 1) Using Validate jQuery 2) Using Regex

1. Using Validate jQuery, you can refer to this article.
2. Using Regex below is the step.

First, we need to create a Regex pattern for the phone numbers.

Here is the Regex pattern for the phone number

^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$

jQuery provides a test() function to match the field value with the pattern.

Here is the code

$( '.phone-input' ).on( 'input', function() {
  var phone_val = $(this).val();
        var phone_valid_status = /^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$/.test( phone_val );
        if( !phone_valid_status ) {
            $( '.custom-validation' ).show();
        } else {
            $( '.custom-validation' ).hide();
} );

Here is the HTML

<input type="text" class="phone-input" name="your-phone" value="">
<p class="custom-validation">Please Enter Valid Phone Number</p>

Here is the Output


I hope this solution is helpful for us.

Submit a Comment

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


Select Categories