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
- Using Validate jQuery, you can refer to this Article.
- 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.