I want to use both jquery repeater and jquery validation library. Here my validate rules:
$("#myForm").validate({
rules: {
title: {
required: true
},
subject: {
required: true
}
},
messages: {
title: {
required: "Enter title!"
},
subject: {
required: "Enter subject!"
}
},
errorElement: 'div',
errorPlacement: function (error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error)
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
submitForm();
return false;
}
});
but it is not working. Because jquery repeater creates input name like data[0][title], data[1][title], data[0][subject], data[1][subject], etc. Therefore my rules are not working just naming title or subject. How can I validate these name like data[*][title] and data[*][subject] ?
As stated in my comment, you cannot set rules from within the
.validate()
method when thename
is unknown. (If thename
is missing, you cannot use this plugin.)Keep in mind that unique
names
are mandatory for this plugin to function. Any of the techniques below still need a uniquename
on each field.If simple rules like
required
need to be set, then you can declare them inline withdata
attributes, HTML5, or classes.required="required"
,class="required"
, etc. and the plugin will pick them up automatically.If you cannot alter the inline HTML, then you can use the
.rules()
method to add rules to these fields as long as they exist at the time you've called.rules('add')
.Call
.validate()
on your form to initialize the plugin with your options.Create your new fields using Repeater or whatever method, making sure that all new fields have a unique
name
attribute.Call
.rules('add')
insides of a jQuery.each()
that is attached to a jQuery selector such as "ends with" on these new fields. This will dynamically add therequired
rule to all fields with aname
that ends with the string[subject]
...