JQuery Validation for Array of Input Elements

Sometimes we need to validate an array of input elements: For example –

Now we will use jquery validation plugin jquery.validate.js for validating the form. The condition will be that user will have to choose category from each dropdown. The script for validation will be as below –




Now the problem is that the readymade jquery.validate.js only validates the first element of category[]. So, we need to modify it a little bit.

In jquery.validate.js, we can find a function named checkForm, we have to modify it as below:


checkForm: function() {
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();
}

25 comments

  1. This was exactly what I was looking for. Thank you so much. The only problem I'm having is that after I submit a form with errors on two of the inputs with name="category[]" only the first input gets an error message generated with whatever the last input has wrong.

    ex:
    if I have a form with these validation rules
    rules {
    "contactEmail[]": {
    required: true,
    email: true
    }
    messages {
    "contactEmail[]": {
    required: "E-mail required",
    email: "Invalid E-mail"
    }

    and I try to submit a form where the first contactEmail input is blank and the second contactEmail input is an incorrect email format I get the error message "Invalid E-mail" underneath the first contactEmail input and nothing under the second.

    Hope you can help, but if not then this is an awesome start…
    Thanks again

  2. I really think jquery validate could be more helpfull with your correction, It really solved a problem i had for some days trying the way to solve.

    Thank you very much for your help

  3. a reply on Grahf’s comment. i also had the same issue when the validator validates an array of inputs eg: i had to dynamically add id numbers. each field had the following rules: ‘required’,’remote’ and a custom rule.

    the problem was that when the 2nd or 3rd field returns from the remote validation the error message would attach itself to the 1st field. in the test i would actually have a valid field. by hacking the plugin a bit i changed the following code to accommodate looking rather at the IDs than the Name attributes of the elements.

    in my case this worked perfectly.

    i came up with the following:
    – change this function (line 379):
    showErrors: function(errors) {
    if(errors) {
    // add items to error list and map
    $.extend( this.errorMap, errors );
    this.errorList = [];
    for ( var name in errors ) {
    this.errorList.push({
    message: errors[name],
    /* NOTE THAT IM COMMENTING THIS OUT
    element: this.findByName(name)[0]
    */
    element: this.findById(name)[0]
    });
    }
    // remove items from success list
    this.successList = $.grep( this.successList, function(element) {
    return !(element.name in errors);
    });
    }
    this.settings.showErrors
    ? this.settings.showErrors.call( this, this.errorMap, this.errorList )
    : this.defaultShowErrors();
    },

    THEN: i added a function (findById line 697) to rather look at the id attribute of the element

    findById: function( id ) {
    // select by name and filter by form for performance over form.find(“[id=…]”)
    var form = this.currentForm;
    return $(document.getElementById(id)).map(function(index, element) {
    return element.form == form && element.id == id && element || null;
    });
    },

    hope this helps….

  4. Thanks a ton.. Had been searching for this solution for quite a few days now.. A patch of should jquery should be released with this.. πŸ™‚

  5. I just couldn’t get this working until I finally found out why!

    My form fields only had a name=”namearray[]”. Al those fields also need a unique ID! It doesn’t matter what the ID is, but without an ID on the input field, this fix will not work.

Leave a comment

Your email address will not be published. Required fields are marked *