javascriptphpjqueryformvalidation-plugin

JQuery validation on URL using plug-in needs to be customized


I am using JQuery validation plug-in to validate a form on my webdirectory site. I need to allow users to enter an URL in the form "www.url.com", but the plug in requires the user to type URL as "http://www.url.com".

Is there a way around it? Please advise. Thanks for your time and suggestions.


Solution

  • There are two approach that you can take:

    1. Just add new custom method to accommodate it:

        jQuery.validator.addMethod("url2", function(value, element) {
          
          //just change below regex to your needs
          return this.optional(element) || /^[a-zA-Z]{1,3}\.[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$/.test( value );
        }, 'Please enter a valid url address.');  

    And ensure your element put data attribute type like below:

    <input id="myid" type="url2"/>
    
    1. Override the plugin method for url validation like below:

    $.validator.methods.url = function( value, element ) {
      return this.optional( element ) || /^[a-zA-Z]{1,3}\.[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$/.test( value );
    }