gpt4 book ai didi

javascript - jQuery 验证插件 - 基于选中的单选按钮的最小文本输入量

转载 作者:行者123 更新时间:2023-12-03 05:07:03 25 4
gpt4 key购买 nike

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"
}
}

关于javascript - jQuery 验证插件 - 基于选中的单选按钮的最小文本输入量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com