Reputation: 2466
I am working on a form which adds up to 10 fields dynamically based on user selection. I have to validate all the dynamically added elements. Till here everything is working fine except the error messages. For example if the user does not enter field 2 value and submits the form, the error message should be "Please Enter Visitor 2's Name". If user does not enters field 3 then the error should change to "Please Enter Visitor 3's Name". I have it working all except for the messages which are showing same for all the fields. Suppose user added 5 field. All the fields show up the same error message, "Please Enter Visitor 5's Name" for all input fields.
Here is my code:
$('.visitors_name').each(function (key, value) {
$(this).rules('add', {
required: true,
minlength: 2,
maxlength: 50,
messages: {
required: "Please Enter Visitor "+key+"'s Name",
}
});
});
Any help please?
Upvotes: 1
Views: 654
Reputation: 98718
You would have to use a function
to dynamically construct and return
a message...
$('.visitors_name').each(function (key, value) {
$(this).rules('add', {
required: true,
minlength: 2,
maxlength: 50,
messages: {
required: function() {
return "Please Enter Visitor " + key + "'s Name";
}
}
});
});
DEMO: jsfiddle.net/6z9Lv8pk/
Upvotes: 2