简体   繁体   English

如何使用jQuery Validator确定一个字段的值大于另一个字段?

[英]how to use jquery validator to determine value of one field is greater than another field?

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 我在表单中有两个字段,我想为他们添加一条规则,说id2的值不能小于id1

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


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

Is there a way to set the rule for the jquery validator? 有没有办法为jquery验证器设置规则?

Add a custom method: 添加自定义方法:

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

The above code assumes you are using integers. 上面的代码假定您使用整数。 If not, replace parseInt with parseFloat . 如果不是,请将parseInt替换为parseFloat

Then use it this way in your configuration: 然后以这种方式在您的配置中使用它:

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

You can have the desired behavior with jQuery using the following : 您可以使用以下代码使用jQuery达到所需的行为:

HTML 的HTML

 <input type="text" id="id1">
 <input type="text" id="id2">
 <input type="submit" id="submit">
 <div class="error" style="display:none">id2 cannot have value less than id1<div>

jQuery jQuery的

$("#id2").focusout(function(){

    if(parseFloat($("#id1").val()) > parseFloat($("#id2").val()))
    {
        $(".error").css("display","block").css("color","red");
        $("#submit").prop('disabled',true);
    }
    else {
        $(".error").css("display","none");
        $("#submit").prop('disabled',false);        
    }

});

See the jfiddle : http://jsfiddle.net/fyrgazfg/ 参见jfiddle: http : //jsfiddle.net/fyrgazfg/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM