Looking at the documentation here: http://docs.jquery.com/Plugins/Validation/Reference#Fields_with_complex_names_.28brackets.2C_dots.29 the syntax for attaching rules to input arrays is like this:
rules: {
"user[email]": "email",
However in my case the array keys are number values and could have any value, but still I'd like to attach the rule to the fields. I dynamically add input fields with jQuery (key
is a global variable):
$('a#addfield').click(function(e)
{
e.preventDefault();
var data = '<p><input type="file" name="field['+key+']"></p>';
$('div#inputcontainer').append(data);
});
Sample HTML output:
<p><input name="field[19]" type="file"></p>
<p><input name="field[22]" type="file"></p>
<p><input name="field[25]" type="file"></p>
I have tried defining the rules like this:
rules:
{
'field[]': {
required: true,
extension: "pdf|doc|docx"
}
}
(taken from this answer: jquery validate add rules for an array input EDIT: This suggested way of setting rules with 'field[]'
is not working with the validation plugin. See answer and comments below. )
But there is no validation error when I try to add other filetypes... Any suggestions?
jQuery.validate
does not support validation of multiple fields with the same name like that, not even if you'd remove the numbers between brackets (which you can do when sending it to most back-end languages). Try using$('input').rules("add", { required:true, extension: "pdf|docx?" })
– Fabrício Matté Mar 12 '13 at 13:56name="field[]"
which would work with the validation... – jtheman Mar 12 '13 at 14:01.rules("add", {})
for each dynamically generated field. There is no other option that doesn't involve uglier hacks. – Fabrício Matté Mar 12 '13 at 14:02$('input[name="field['+key+']"]').rules("add", { required:true, extension: "pdf|doc|docx" });
(key
was my variable with the number...) – jtheman Mar 12 '13 at 14:06