Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery Validate Plugin to validate multiple form fields with identical names

I have a dynamically generated form with input fields with the same name (for example: "map"). I do not have the option of changing the field names or generating unique field names because the form handler code (Perl/CGI) is designed to handle an array of input values (in this case @map).

How can I use the JQuery Validate Plugin to validate a form in such a situation? Specifically I would want exactly one element of the submitted array to have a certain fixed value. I am currently using a custom event handler that creates a JSON object with serializeArray() and then traverses it to ensure that the condition is met. But since I have used the Validate Plugin in the rest of the application, I was wondering if such a case may be handled using the same plugin here too.

Thank you for your attention.

like image 312
Ya. Perelman Avatar asked May 31 '09 09:05

Ya. Perelman


1 Answers

Instead of changing the source file jquery.validation you can simply override the function you need to edit only in the pages that requires it.

An example would be:

$.validator.prototype.checkForm = function() {     //overriden in a specific page     this.prepareForm();     for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {         if (this.findByName(elements[i].name).length !== undefined && this.findByName(elements[i].name).length > 1) {             for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) {                 this.check(this.findByName(elements[i].name)[cnt]);             }         } else {             this.check(elements[i]);         }     }     return this.valid(); }; 

This might not be the best solution, but at least it avoids editing source files, that could be replaced later, when a new version releases. Where your overridden function might or might not break.

like image 146
Ahmed Galal Avatar answered Sep 20 '22 04:09

Ahmed Galal