验证取决于复选框?

时间:2012-05-17 05:42:16

标签: jquery

我的表单中有一个部分,仅在选中复选框时才会显示。所以我对你的字段的验证应该只在选中复选框时才适用。我的代码不起作用。

这是我到目前为止所发现的信息:

http://docs.jquery.com/Plugins/Validation

// Validation

function validateForm() {
    $('#frmMain').validate({
        rules: {

            SuretyFullName: { required: '#chkSurety:checked' } //if required: true it works all the time.
        },
        messages: {
            SuretyFullName: { required: 'Required' }
        },

        submitHandler: function (form) {
            $('#btnSubmit').click();

        }
    });
}

代码编辑:以下建议:表单变得无法响应:

$(document).ready(function(){
  $("#btnSubmit").click(function(){
if($('#chkSurety').is(":checked"))
{  
function validatesurety(){
 $('#frmMain').validate({
 rules: {       
            SuretyFullName: { required: true } 
            },
        messages: {
            SuretyFullName: { required: 'Required' } 
        }
    });
}

3 个答案:

答案 0 :(得分:2)

您可以检查是否已检查,然后运行您的功能

  $(document).ready(function(){
 //the submit click 
      $("#submit").click(function(){
    if($('#checkboxid').is(":checked"))// check if the checkbox checked if yes 
    {
    //then call you function 
    function validateForm() ;
    }
      });
    });

答案 1 :(得分:2)

将其放入validateForm功能:

// set the default rules
var rules = {
    SuretyFullName: { required: false },
    SuretyIDNumber: { required: true}, 
    SuretyPhysicalAddress: { required: true }, 
    SuretyHomeTel: { required: true}, 
    SuretyPlace: { required: true}, 
    SuretyDay: { required: true }, 
    SuretyMonth: { required: true } 
 };

 // override the full name rule, based on the checkbox
 rules.SuretyFullName.required = $('#chkSurety').is(':checked');

 $('#fmrMain').validate({
      rules: rules,
      ...
 });

答案 2 :(得分:1)

function validateForm() {
    $('#frmMain').validate({
        rules: {

           SuretyFullName: { required: function (element) { if ($('#chkSuretyShip').is(':checked')) { return true } else { return false} } },           
        },
        messages: {
            SuretyFullName: { required: 'Required' }
        },

        submitHandler: function (form) {
            $('#btnSubmit').click();

        }
    });
}