JQuery Validation for Array of Input Elements

Share

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();
}
This entry was posted in Javascript, jQuery and tagged , . Bookmark the permalink.
 

35 Responses to JQuery Validation for Array of Input Elements

  1. Mahabub says:

    thnaks a lot for the post

  2. Santiago says:

    How to make this to validate inputs of emails?

    Thanks, great post.

  3. parrudinho says:

    Very thanks, was exactly what I wanted

  4. Stewart says:

    Amazing. EXACTLY what I was looking for.

    Thanks very much :)

  5. Mahias says:

    Thanks a lot, I was looking for this!

  6. SolidVapour says:

    Why dont you submit this as a patch?

  7. Eric says:

    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

  8. thx a lot man..
    hats off…
    helped me to clean a lot code..

  9. Vikas Patel says:

    This is great.

    Send this snippet to Jörn Zaefferer!

  10. Grahf says:

    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

  11. Kobo says:

    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….

  12. Kobo says:

    correction. reply to Eric’s comment

  13. koelimaya says:

    oh… thx a lot,
    nice post….

  14. ghj says:

    it is always focusing on the first form field

  15. RG says:

    Thanks a lot, same thing I was looking.

  16. Ray says:

    Good job !

  17. Thank you for this! says:

    Now…if we can get the jquery.validate folks this code all would be well :)

  18. Niraj Bhambhani says:

    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.. :-)

  19. Thanks you sir. You’ve made my day

  20. 24creative says:

    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.

  21. adi says:

    thanks bro

  22. amine says:

    Very thanks,goooooooooooooood job !

  23. Rob says:

    HUZZAH!

  24. sagar says:

    nice work

  25. Itachi says:

    Excelente post
    No sabes cuanto me ayudastes
    ;)

  26. amit says:

    nice work.
    Thanks a lot.

  27. fawzia says:

    very nice. it solve the issue. great work

  28. Anbarasan k kanagaraj says:

    This was exactly what I wanted.. Great work

  29. Sudesh says:

    Great Work!!! .. Instead of changing the core jquery validation plugin is there any alternative place where we can place this piece of code?

  30. sibel says:

    thank save my time.

  31. boevik says:

    Thanks a lot. It’s great solution

  32. Vinod says:

    Thanks a Lot you saved my days of work !!!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>