How can i validate the following using jQuery Validation . The user must at least select 1 of the option below.
To mandate that at least one out of these select
elements are selected, you would use the require_from_group method which is part of the additional-methods.js file.
$('#myform').validate({
// other options,
rules: {
"quantity[adult][seat_a]": {
require_from_group: [1, ".group-required"]
},
"quantity[adult][seat_b]": {
require_from_group: [1, ".group-required"]
},
"quantity[adult][seat_c]": {
require_from_group: [1, ".group-required"]
}
},
groups: {
myGroup: "quantity[adult][seat_a] quantity[adult][seat_b] quantity[adult][seat_c]"
}
});
This will create a simultaneous & identical error message on all three select
elements. Use the groups option to combine these into one and the errorPlacement option to place the resulting message into your layout.
Important: You also need the value
of the default option
of every select
to be empty. Otherwise, the plugin thinks 0
is the user's selection and nothing will be validated.
<select name="quantity[adult][seat_a]" class="group-required">
<option value="">0</option>
....
OR...
<select name="quantity[adult][seat_a]" class="group-required">
<option value="">Please select...</option>
<option value="0">0</option>
....
EDIT:
If you have a huge number of elements and do not wish to declare them individually within .validate()
, then use the .rules('add')
method within a jQuery .each()
.
$('#myform').validate({
// other options,
});
$('.group-required').each(function() {
$(this).rules('add', {
require_from_group: [1, '.group-required']
});
});
Working DEMO: http://jsfiddle.net/n1z0Lufw/
Additionally, using the groups
option to consolidate error messages, again without having to declare each field name manually...
var names = "";
$('.group-required').each(function() {
names += $(this).attr('name') + " ";
});
names = $.trim(names);
$('#myform').validate({
// other options,
groups: {
myGroup: names
}
});
$('.group-required').each(function () {
$(this).rules('add', {
require_from_group: [1, '.group-required']
});
});
DEMO 2: http://jsfiddle.net/scmuxq53/