views:

479

answers:

1

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?

+2  A: 

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");
Jose Basilio
Still doesn't work. Enter 1000 as cost_of_car and 500 as payment_amount - no error messages as expected. Enter 300 instead of 500 - "Can't be less than cost_of_car * 0.4" message appears. Enter back 500 instead of 300 - message doesn't hide but it should.
Alexander Prokofyev
@Alexander - Please accept my answer since it is working now.
Jose Basilio
Have you repeated the test from my previous comment? Still doesn't work.
Alexander Prokofyev
I repeated the test. This appears to be a bug with the Validation Plug-in. The validation message does not go away. However, the form submission only happens with valid inputs (which is a good thing).
Jose Basilio
Thanks anyway! I am going to accept your answer as the best of given ones. :)
Alexander Prokofyev