开发者

Jquery validate: re-validate a validated form after checkbox changed with different rules

开发者 https://www.devze.com 2022-12-19 06:19 出处:网络
I am trying to validate a form with a couple of elements being required if a checkbox is NOT checked.

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');
0

精彩评论

暂无评论...
验证码 换一张
取 消