Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have search lot of about this but haven't found any solution. I want to validate multiple array named file inputs and dropdowns in JQuery validate.

<td> <input type="text" class="times" name="times[]" /> </td>
</tr>
<tr>
<td> <input type="text" class="times" name="times[]" /> </td>
</tr>
<tr>
<td> <input type="text" class="times" name="times[]" /> </td>
</tr>

I have added JQuery Validate Code like this:

$("#formname").validate(
    {
    rules:{
        times:{required:true, digits:true}
    }}
    );

But its only validating first input and showing error message there only whether 2nd or 3rd input field entered or not.

I don't want to change this "times[]" name because functionality is depending on this. Only I want validation using JQuery validate.

Is there any trick available for this?

Any help would be appreciated.

Thanks

share|improve this question

1 Answer 1

up vote 1 down vote accepted

The plugin doesn't handle fields with the same name well. Here's how I solved it in my application.

I gave all the repetitive fields distinct names, and put the validation method names in the class.

<td> <input type="text" class="times required digits" name="times[0]" /> </td>
</tr>
<tr>
<td> <input type="text" class="times required digits" name="times[1]" /> </td>
</tr>
<tr>
<td> <input type="text" class="times required digits" name="times[2]" /> </td>
</tr>

You can remove the indexes before submitting with code like this:

$("#formname").validate({
    ...
    submitHandler: function(form) {
        $(form).find(":input[name*='[']").each(function() {
            this.name = this.name.replace(/\[\d+\]/, '[]');
        }
        form.submit();
    }
});
share|improve this answer
    
Thanks but I want unique name for all my input fields. Actually the form is very huge and lots of inputs & dropdown names are like this so I can't change that name. Is it possible by passing some index to Jquery validate? –  Ultimate Oct 14 '13 at 15:58
    
You can have your submit handler iterate through all the fields and remove the number from inside the brackets -- that's what I do. –  Barmar Oct 14 '13 at 16:00
    
The basic problem is that the plugin expects names to be unique. It uses the name as the key in an internal table. If there are duplicates, it will validate all of them, but put the error message next to the first one all the time. –  Barmar Oct 14 '13 at 16:02
    
Thanks. Can you please put some code so that I'll get some idea. –  Ultimate Oct 14 '13 at 16:03
    
Added sample code –  Barmar Oct 14 '13 at 16:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.