如何在条件下禁用自定义验证方法

时间:2009-04-29 05:20:43

标签: jquery-validate dependencies

我使用jQuery Validation plugin来确保用户在第一个文本字段中输入正 cost_of_car ,在第二个文本字段中输入正 payment_amount ,例如* cost_of_car * 0.4&lt ; = 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 
        }
    }
});

现在我想跳过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 的验证?

1 个答案:

答案 0 :(得分:2)

更新:更改必须在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");