繁体   English   中英

jQuery Validation Plugin-基于单选按钮的最小文本输入量

[英]jQuery Validation Plugin - Minimum amount for text input based on radio button checked

HTML:

<form method="post" class="form" action="/forms/" id="basicDonationForm" name="basicDonationForm">
   <div class="line">
      <div class="control">
         <label>Method of Payment:</label>
         <div class="radio">
            <input type="radio" name="basicDonationFormPayMethod" id="basicDonationFormPayMethodCC" value="Credit Card">
            <input type="radio" name="basicDonationFormPayMethod" id="basicDonationFormPayMethodOther" vaue="Other">
         </div>
      </div>
   </div>
   <div class="line" style="padding-bottom:20px;">
   <div class="control">
      <label for="basicDonationFormAmount">Amount you will donate:</label>
      <input type="text" name="basicDonationFormAmount" id="basicDonationFormAmount">
      </div
   </div>
   <div class="line line-buttons"><a class="button" href="javascript:void(0);"><span>Submit</span></a></div>
</form>

金额字段必须为:

  • 如果检查了basicDonationFormPayMethodCC,则至少为18
  • 如果检查basicDonationFormPayMethodOther,则至少为10

到目前为止,我有以下规则:

rules: {
    basicDonationFormPayMethod: {
        required: true
    },
    basicDonationFormAmount: {
        number: true,
        required: true,
        special: true
    }
}

我已经开始使用jQuery.validator.addMethod() ,但是我发现的所有示例都使用传递的参数来检查元素的值。 我不确定使用一个元素的规则将一个表单元素与另一个表单元素进行比较所需的语法。

我的JavaScript:

    jQuery.validator.addMethod("special", function (value, element, param) {
        if ($("input[name='basicDonationFormPayMethod']:checked").length > 0){
            var currentDonation = $("#basicDonationFormAmount").val();
            var radioVal = $('input:radio[name=basicDonationFormPayMethod]:checked').val();
            if (radioVal == 'Credit Card') {
                if (currentDonation >= 18) {
                    return true;
                } else {
                    return false;
                }
            } else {
                if (currentDonation >= 10) {
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        };
    }, "Choose payment method and enter $18 or more for credit, $10 or more for other");

它有效,但是感觉太肿。 如果语法继承自插件,我想简化自定义方法。

您无需编写自定义方法即可简单地实现条件规则。 可以使用rules对象中的函数来完成。

像这样

rules: {
    basicDonationFormPayMethod: {
        required: true
    },
    basicDonationFormAmount: {
        number: true,
        required: true,
        min: function() {
            return ($('input:radio[name=basicDonationFormPayMethod]:checked').val() == "Credit Card") ? 18 : 10;
        }
    }
},
messages: {
    basicDonationFormAmount: {
        min: "Choose payment method and enter $18 or more for credit, $10 or more for other"
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM