How to disable custom validation method on condition
-
03-07-2019 - |
Question
I use jQuery Validation plugin to ensure what user entered positive cost_of_car in first text field and positive payment_amount in second text field such what *cost_of_car * 0.4 <= payment_amount <= 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
}
}
});
Now I want to skip testMaxAmount and testMinAmount checks until cost_of_car is valid. Testing
$("#calc_form").validate().element("#cost_of_car")
or even
$("#calc_form").validate({ignore: "#payment_amount"}).element("#cost_of_car")
inside these methods leads to the recursion and hangs browser.
Would you propose some other method to disable validation of payment_amount until cost_of_car is valid, please?
Solution
UPDATE: The change has to be in the validator.addMethod()
calls:
$.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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow