Add URL Validation Using Regex jQuery

This article will teach us how to add URL validation using regex jQuery.

There are two ways to add Email 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 URL.

Here is the Regex pattern for the URL

^(http(s)?:\/\/)?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$

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

Here is the code

$( '.url-input' ).on( 'input', function() {
    var url_val = $(this).val();
        var url_valid_status = /^(http(s)?:\/\/)?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test( url_val );
        if( !url_valid_status ) {
            $( '.custom-validation' ).show();
        } else {
            $( '.custom-validation' ).hide();
        }
  } );

Here is the HTML

<div class="custom-placeholder-wrap">
    <label class="placeholder" style="">Your URL<span class="required">*</span></label>
    <input type="text" class="url-input" name="your-url" value="" size="40" aria-required="true" aria-invalid="false">
<p class="custom-validation">Please Enter Valid URL</p>
  </div>

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 *

Subscribe

Select Categories