I have this form https://jsfiddle.net/y2L3rcts/2/ which dynamically adds input boxes to the form when a user clicks "Add More".
The initial input boxes has the following name=
meta:
label[0][name]
label[0][left]
Adding new input boxes dynamically creates new input boxes with name=
label[1][name]
label[1][left]
and so on...
Validating the initial input boxes can be easily done using query rules:
//Form Validation
$('form').validate({
rules: {
"label[0][name]": {
required: true
},
"label[0][left]": {
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
});
And, validating the additional "Add More" input boxes can be done by explicitly declaring those label[id]
at the rules even they do not exist at the form.
"label[0][name]": {
required: true
},
"label[0][left]": {
required: true
},
// Add the "Add More" input box labels assuming they do exist
"label[1][name]": {
required: true
},
"label[1][left]": {
required: true
},
"label[2][name]": {
required: true
},
"label[2][left]": {
required: true
}
and so on. But this method is static. There is no limit on how many "Add more"
input boxes can be dynamically created, so it would be inefficient to define explicitly all label[id]
(say, 99) in our rules.
is there a way for Jquery Validator to check how many input boxes with label[]
are created and apply the rules to all of them?
BTW, I tried modifying my own jquery.validator.js
as per suggested by this: http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements/ But I am still in no luck, i don't think that problem's scope cover my problem.
Hope somebody can help. Thanks!
(P.S. I'd been working for couple of hours in fiddle on how can i make the validation work there, haha, i have no idea how you guys do it)