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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.