Reputation: 8508
I'm trying to use jQuery validation plugin to validate a form I have on one of my applications.
The form (simplified) is as follow :
<form id="my_form" action="#" method="post" novalidate="novalidate">
<input id="my_hidden_input" type="text" style="display:none;">
<input id="my_select_checkbox" class="checkbox" type="checkbox" value="1">
<select id="my_select_1" class="select valid" type="select">
<select id="my_select_2" class="select valid" type="select">
</form>
What I'm trying to do is to validate the following : if the checkbox is checked, I check that a value is selected in my first select, and if the checkbox isn't checked, I check the selected value of my second list.
I tried something like :
$('#my_form').validate({ // initialize the plugin
rules: {
my_hidden_input:{
"checkboxSelect": true,
},
},
submitHandler: function (form) { // for demo
console.log($("#monitors_start").value);
return false;
}
});
jQuery.validator.addMethod(
"checkboxSelect",
function() {
if ($("#my_select_checkbox").attr('checked'))
return $("#my_select_1").val();
else
return $("#my_select_2").val();
}, "test addMethod"
);
But it seems i'm not getting it properly... If anybody could help it'd be greatly appreciated !
Thanks !
Upvotes: 0
Views: 839
Reputation: 388416
You can use the depends option like
var validator = $('#form').validate({
rules: {
my_select_1: {
required: {
depends: function () {
return $('#my_select_checkbox').is(':checked')
}
}
},
my_select_2: {
required: {
depends: function () {
return !$('#my_select_checkbox').is(':checked')
}
}
}
},
messages: {}
});
Demo: Fiddle
Upvotes: 2