jQuery 验证 - 根据用户选择设置条件规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19543354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:11:35  来源:igfitidea点击:

jQuery validate - set conditional rules based on user selection

javascriptjqueryjquery-validate

提问by Zabs

Is it possible to easily setup a conditional rule with jQuery validate,

是否可以使用 jQuery 验证轻松设置条件规则,

Simply put i'm trying add some logic which says, if checkbox 'A' is ticked - then field 'A' must be completed, if checkbox 'B' completed then fields 'B1' & 'B2' must be completed.

简单地说,我正在尝试添加一些逻辑,如果勾选了复选框“A”,则必须完成字段“A”,如果已完成复选框“B”,则必须完成字段“B1”和“B2”。

e.g if a checkbox with the name 'paypal' is checked - then the field named 'paypal_address' must be completed.

例如,如果选中了名为“paypal”的复选框,则必须填写名为“paypal_address”的字段。

My existing logic is as follows:

我现有的逻辑如下:

<script type="text/javascript">
$(document).ready(function () {

$('#checkout-form').validate({
    rules: {
        first_name: {
            minlength: 2,
            required: true
        },
        last_name: {
            minlength: 2,
            required: true
        },
        address_1: {
            minlength: 2,
            required: true
        },
        address_2: {
            minlength: 2,
            required: true
        },
        post_code: {
            minlength: 2,
            required: true
        },            
        email: {
            required: true,
            email: true
        },
        terms: {
          required: true,
        }
    },
    errorPlacement: function(error, element) { 
      element.addClass('error');
    },        
    highlight: function (element) {
        $(element).addClass('nonvalid')
          .closest('.form-group').removeClass('error');
    },
    success: function (element) {
        //element.addClass('valid')
          //.closest('.form-group').removeClass('error');
          element.remove('error');
    }
});

UPDATE

更新

Using the method below from Rohit i've almost got this working perfectly.. My form has three checkboxes (only one can be selected) 1. Paypal 2. Bank 3. Check/Cheque

使用下面来自 Rohit 的方法,我几乎可以完美地完成这项工作.. 我的表单有三个复选框(只能选择一个) 1. Paypal 2. 银行 3. 支票/支票

If Paypal is checked (by default it is) then only have the 'paypal_email_address' field required, if Bank is checked then 'account_number' & 'sort_code' fields are required & finally if Cheque is checked the 'check_payable_field' is required.

如果选中 Paypal(默认情况下),则只需要“paypal_email_address”字段,如果选中银行,则需要“account_number”和“sort_code”字段,最后如果选中 Check,则需要“check_payable_field”。

// i've got this so far $( ".paymentMethod" ).on( "click", function() { var payment_method = $(this).val();

// 到目前为止我已经有了这个 $( ".paymentMethod" ).on( "click", function() { var payment_method = $(this).val();

  if (payment_method == 'paypal') {
    paypal_checked = true;
  } else if (payment_method == 'bank-transfer') {
    bank_checked = true;
    paypal_checked = false;
  } else if (payment_method == 'cheque') {
    cheque_checked = true;
    paypal_checked = false;
  }

});

});

回答by Ryley

jQuery Validate actually directly supports this, using dependency expressions.

jQuery Validate 实际上直接支持这一点,使用依赖表达式

All you need to do is change your validate options like this:

您需要做的就是像这样更改验证选项:

$('#myform').validate({
    rules: {
        fieldA: {
           required:'#checkA:checked'
        }
    }
});

That's it!

就是这样!

回答by Gorsky

You can use a custom validation method. For example:

您可以使用自定义验证方法。例如:

jQuery.validator.addMethod("checkA", function(value, element) {
    return YourValidationCode; // return true if field is ok or should be ignored
}, "Please complete A");

then use it in your rules:

然后在您的规则中使用它:

rules: {
    ....
    field_a: {
        required: false,
        checkA: true
    },
    ....
}

Take a look: http://jqueryvalidation.org/jQuery.validator.addMethod/

看一看:http: //jqueryvalidation.org/jQuery.validator.addMethod/

回答by Rohit

Edit: I did not understand the question properly at first, I apologize for that :P But, here's a solution that should work.

编辑:一开始我没有正确理解这个问题,我为此道歉:P 但是,这里有一个应该有效的解决方案。

What you can do is check whether or not the checkbox is checked and then set the required rule for paypal_address as such:

您可以做的是检查复选框是否被选中,然后为 paypal_address 设置所需的规则,如下所示:

 var checked = false;
 $( "#paypalCheckbox" ).on( "click", function() {
      checked = $('#paypalCheckbox').is(':checked');
  });

And then in the rules you can add:

然后在规则中你可以添加:

 paypal_address : {
 required: checked
 }

回答by Jaggan_j

jQuery validate with condition as a function result (adding on to Ryley's comment above):

jQuery 使用条件作为函数结果进行验证(添加到上面 Ryley 的评论中):

$("#Form_Id").validate({
    rules: {
        CompletedBy: "required", //straight forward validation of field
        Contact_No: "required",
        Location: { required: noTableRow }//if no table row, make Location mandatory
    }        
});

//checks whether a table row exists
function noTableRow() {
  return $("tr.tr_class").length == 0;
}