How to provide dynamic validation in jQuery validate

Posted By : Shiv Kumar | 11-Dec-2014

While using jQuery validation, in most of the cases we have to provide static validation(i.e min/max value or digits only etc.).

But somtime we have to provide dynamic validation which will change every time.

Problem : Validation defination for height is:

height: { 
    required: true,
    number: true, 
    max: $('#maxHeight').val()
},

If we provide dynamic value like this then it will run only once as the .validate() method initializes only once and

assign the value of maxHeight once for validation which doesn't change every time.

Solution : We have to do little bit change to the above defined validation like this:

Way 1:

height: { 
    required: true,
    number: true, 
    max: function(){ return $('#maxHeight').val() }
},

Doing this,each time function is called for applying max validation which in turn return the dynamic value each time.

Way 2: We have to use the "rules" method which will update the rules dynamically like :

$('#maxHeight').rules("add", {
     max: $('#maxHeight').val();
});

Way 3 : Another way is define your custom rule for the field in this way :

jQuery.validator.addMethod("maxHeight", function (height, element) {
    var max_height = $('#maxHeight').val()
    return max_height == height;
}, "Invalid height");

then in validate method just use :

height: { 
    required: true,
    number: true, 
    maxHeight: true
},

Note : This custom rule must be define before the .validate() method .

Thanks

Shiv Kumar

About Author

Author Image
Shiv Kumar

Shiv is an experienced Java Developer with a strong background in multiple technologies. He specializes in defining system architectures to ensure reliable and resilient solutions. He possesses a comprehensive understanding of the latest technologies and has hands-on experience in Core Java, Spring Boot, Hibernate, Apache Kafka messaging queue, Redis, as well as relational databases like MySQL and PostgreSQL, and non-relational databases like MongoDB. He excels in API implementations, Microservices, Web Services development, testing, and deployments. Shiv actively contributes to code enhancements and consistently delivers valuable contributions to various client projects, including Fabtrack, Pando, Pandojo, Digikam, WhatsApp Integration, Croniz, Punchin Application, Script TV, Bhaasha, and more. He demonstrates strong analytical skills and a creative mindset. In addition, he has a passion for reading books and exploring new technologies and innovations.

Request for Proposal

Name is required

Comment is required

Sending message..