如何在条件下禁用自定义验证方法
-
03-07-2019 - |
题
我使用jQuery 验证插件来确保用户输入正面 cost_of_car 在第一个文本字段中,正 payment_amount 在第二个文本字段中,例如* cost_of_car * 0.4 <!> lt; = payment_amount <!> lt; = cost_of_car *:
$.validator.addMethod("testMaxAmount", function()
{
return $("#cost_of_car").val() - 0 >= $("#payment_amount").val() - 0;
}, "Can't be more than cost_of_car");
$.validator.addMethod("testMinAmount", function()
{
return $("#cost_of_car").val() * 0.4 <= $("#payment_amount").val() - 0;
}, "Can't be less than cost_of_car * 0.4");
$("#calc_form").validate(
{
rules:
{
cost_of_car:
{
required: true,
number: true,
min: 1,
max: 10000000
},
payment_amount:
{
required: true,
number: true,
testMaxAmount: true,
testMinAmount: true
}
}
});
现在我想跳过testMaxAmount和testMinAmount检查,直到 cost_of_car 有效。测试
$("#calc_form").validate().element("#cost_of_car")
甚至
$("#calc_form").validate({ignore: "#payment_amount"}).element("#cost_of_car")
在这些方法中导致递归并挂起浏览器。
在 cost_of_car 有效之前,您是否会提出其他方法来禁用 payment_amount 的验证?
解决方案
更新:更改必须在validator.addMethod()
电话中:
$.validator.addMethod("testMaxAmount", function()
{
if($("#cost_of_car").valid())
return $("#cost_of_car").val() - 0 >= $("#payment_amount").val() - 0;
else
return true;
}, "Can't be more than cost_of_car");
$.validator.addMethod("testMinAmount", function()
{
if($("#cost_of_car").valid())
return $("#cost_of_car").val() * 0.4 <= $("#payment_amount").val() - 0;
else
return true;
}, "Can't be less than cost_of_car * 0.4");
不隶属于 StackOverflow