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

Ya. Perelman picture Ya. Perelman · May 31, 2009 · Viewed 85k times · Source

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.

Answer

Ahmed Galal picture Ahmed Galal · Jul 31, 2012

As i cant comment on @scampbell answer, i dunno if its about reputation points or because the thread has just closed, i have a contribution to his answer,

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 overriden function might or might not break