如何使用jquery验证器来确定一个字段的值大于另一个字段?

rrg*_*ish 0 javascript jquery

我在表单中有两个字段,我想为他们添加一条规则,说id2的值不能小于id1

 <input type="text" id="id1">
 <input type="text" id="id2">


id1 : {
                number: true,
                min: 0
            }, 
id2 : {
                number: true,
                min: 0
            } 
Run Code Online (Sandbox Code Playgroud)

有没有办法为jquery验证器设置规则?

小智 11

添加自定义方法:

$.validator.addMethod("greaterThan",
    function (value, element, param) {
          var $otherElement = $(param);
          return parseInt(value, 10) > parseInt($otherElement.val(), 10);
    });
);
Run Code Online (Sandbox Code Playgroud)

上面的代码假设您使用的是整数.如果没有,请替换parseIntparseFloat.

然后在您的配置中以这种方式使用它:

id2: {
    number: true,
    min: 0,
    greaterThan: "#id1"
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!但是,这些元素不是必需元素,即使这些字段为空,现在也会显示错误。所以现在我使用了: if(!value) return true; 在自定义方法中。 (2认同)