How can I validate forms with jQuery plugin with ids that have a name pattern, like #formNewHouse1, #formNewHouse2,.. ?
This code is working with a single type (normal) form:
$("#formNewHouse").validate({
rules: {
formNewHouseName: {
required: true
},
formNewHouseAddress: {
required: true
}
},
messages: {
formNewHouseName: {
required: "Please type a name"
},
formNewHouseAddress: {
required: "Please type an address"
}
}
});
I need something like this, where X = 2,3,6,18,19,… (IDs from DB) how can I achieve this?
$("#formNewHouseX").validate({
rules: {
formNewHouseNameX: {
required: true
},
formNewHouseAddressX: {
required: true
}
},
messages: {
formNewHouseNameX: {
required: "Please type a name"
},
formNewHouseAddressX: {
required: "Please type an address"
}
}
});
Thanks in advance.
Also, similar to this question with a working answer:
jQuery Validate set rule using wildcard to find target fields
Here’s an answer along with something the others are lacking… a working demo:
Use jQuery’s
.each()method to initialize.validate()on all matching forms.Then use the built-in
rules()method to add rules and assign them byclass. See documentation.HTML:
jQuery:
jsFiddle DEMO