javascript 如何使用 jquery 验证器来确定一个字段的值大于另一个字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29451507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use jquery validator to determine value of one field is greater than another field?
提问by rrgirish
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 验证器设置规则?
回答by denat
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"
}
回答by callback
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/