如何使用jQuery Validator确定一个字段的值大于另一个字段? [英] how to use jquery validator to determine value of one field is greater than another field?

查看:250
本文介绍了如何使用jQuery Validator确定一个字段的值大于另一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two fields in a form and I want to add a rule for them saying that id2 cannot have value less than id1

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


id1 : {
                number: true,
                min: 0
            }, 
id2 : {
                number: true,
                min: 0
            } 

是否可以为jquery验证器设置规则?

Is there a way to set the rule for the jquery validator?

推荐答案

添加自定义方法:

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

上面的代码假定您正在使用整数.如果不是,请将parseInt替换为parseFloat.

The above code assumes you are using integers. If not, replace parseInt with parseFloat.

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

Then use it this way in your configuration:

id2: {
    number: true,
    min: 0,
    greaterThan: "#id1"
}

这篇关于如何使用jQuery Validator确定一个字段的值大于另一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆