I am trying to validate a form with a couple of elements being required if a checkbox is NOT checked.
Now if I submit the form the rules fire - and then I check the checkbox on - the validation rules have already fired - and even though the 开发者_运维问答checkbox is now checked - the validation rules still apply and the form will not submit until I enter the fields.
What I was hoping was that the checkbox could toggle the rules on or off. Any help much appreciated.
var validator = $(".cmxform").validate({
rules: {
txtAddress1: {
required: function(){
$('#chkCurrentEmployer').attr('checked') !== "true"
} },
txtAddress2: {
required: function(){
$('#chkCurrentEmployer').attr('checked') !== "true"
} }
}
});
Use the required( dependency-expression )
rule
var validator = $(".cmxform").validate({
rules: {
txtAddress1: {
required: "#chkCurrentEmployer:checked"
},
txtAddress2: {
required: '#chkCurrentEmployer:checked'
}
}
});
Documentation here: http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression
Your code might also work if those functions return something like this
return $('#chkCurrentEmployer').attr('checked');
精彩评论