条件でカスタム検証メソッドを無効にする方法
-
03-07-2019 - |
質問
jQuery 検証プラグインを使用して、入力したユーザーが確実に cost_of_car 最初のテキストフィールドにem>、2番目のテキストフィールドに正の 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
}
}
});
今、 cost_of_car が有効になるまでtestMaxAmountおよびtestMinAmountチェックをスキップします。テスト
$("#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