将验证方法添加到“jquery验证插件”

时间:2012-04-30 11:06:07

标签: javascript jquery

您好我使用jquery验证插件来验证我的表单。 我想在验证中再添加一条规则,但无法使其工作。 输入值应小于或等于前一个元素值。

可以这样做吗?

这是代码 -

<input type='text' value='<?php echo $count; ?>' class='input_in_stock' readonly="readonly" />
<input type='text' name='amount[]' id='<?php echo rand(0,99).$id; ?>' size='1' value='<?php echo $count; ?>' class='required input_count' />

$(document).ready(function(){

    $.validator.addMethod('positiveint', function (value) { 
        return (value > 0) && (value != 0) && (value == parseInt(value, 10));
    }, 'Enter a positive integer value.');

    $.validator.addMethod('notmorethan', function (value) { 
        return (value <= $(this).prev().val());
    }, 'abc.');




    $("#cartform").validate({
        rules: {
            "amount[]": {
                required: true,
                positiveint: true,
                notmorethan: true
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next());
        }
    });

});

P.S。我使用这个jquery验证插件修复程序使它适用于这样的名称[] http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements

编辑:找到了解决方案

$.validator.addMethod('notmorethan', function (value, element) { 
    return (value <= $(element).prev().val() );
}, 'abc');

2 个答案:

答案 0 :(得分:1)

看看这个小提琴是否有帮助 - http://jsfiddle.net/alokswain/LSuMA/11/。我不确定您使用的名称是amount[],但我想这种方法应该可以使用。

自定义验证方法只是函数,如果在函数体内使用this,那么它将引用函数的所有者。现在假设您想要从输入字段获取先前有效的值,只要整个表单有效,就可以将它存储在DOM中的某个位置,比如先前存储的值被称为previousAmountVal。当字段中的值更改时,在函数notmorethan中,您可以使用value参数和先前存储的值以及使用previousAmountVal的先前值来访问当前值,从而确定是否当前值是否有效。此外,如果您这样做,请记住在表单有效时始终更新previousAmountVal

答案 1 :(得分:0)

找到解决方案

$.validator.addMethod('notmorethan', function (value, element) { 
    return (value <= $(element).prev().val() );
}, 'abc');
相关问题