Javascript 如何使用 jQuery Validator 比较两个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8090485/
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 compare two fields
提问by jimdrang
I want to validate 2 input fields by comparing one to the other and make sure the second is greater than the first.
我想通过比较一个输入字段来验证 2 个输入字段,并确保第二个大于第一个。
Do I need to add a custom method or can I just use the variable name in the range method? If so, can you point me to the syntax?
我需要添加自定义方法还是我可以只在 range 方法中使用变量名称?如果是这样,你能指出我的语法吗?
var validateSection = function (theForm) {
$(theForm).validate({
rules: {
startPoint: {
required: true,
range: [0, 100]
},
endPoint: {
required: true,
range: [startPoint + 1, 100] //Is this possible if I set the function to run on any change to either field?
},
}
});
if ($(theForm).valid()) {
return true;
}
else {
return false;
}
}
Code with Custom Method:
带有自定义方法的代码:
$.validator.addMethod("endGreaterThanBegin", function(value, element) {
return endPoint > startPoint
}, "* End Point Should be Greater than Start");
var validateSection = function (theForm) {
$(theForm).validate({
rules: {
startPoint: {
required: true,
range: [0, 100]
},
endPoint: {
required: true,
range: [1, 100],
endGreaterThanBegin: true
},
}
});
if ($(theForm).valid()) {
return true;
}
else {
return false;
}
}
Getting $.validator is undefined before I get to form, and then validateSection is not a function when I start testing input fields
在我开始形成之前获取 $.validator 是未定义的,然后当我开始测试输入字段时 validateSection 不是一个函数
回答by Jayendra
Need to add a custom validate method
需要添加自定义验证方法
Protoype -
原型 -
$.validator.addMethod("endate_greater_startdate", function(value, element) {
return enddate > startdate
}, "* Enddate should be greater than Startdate");
Validation -
验证 -
endate_greater_startdate : true
Check for the Demo, as different example but will help debug.
检查Demo,作为不同的示例,但将有助于调试。
回答by jimdrang
Javascript
Javascript
$(function() {
$.validator.addMethod('smaller_than', function (value, element, param) {
return +$(element).val() < +$(param).val();
});
$.validator.addMethod('not_smaller_than', function (value, element, param) {
return +$(element).val() > +$(param).val();
});
$('form').validate();
});
HTML
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form>
value 1
<input name="value1"
data-rule-smaller_than="[name='value2']"
data-msg-smaller_than="value 1 must be smaller than value 2" /><br/>
value 2
<input name="value2"
data-rule-not_smaller_than="[name='value1']"
data-msg-not_smaller_than="value 1 must be smaller than value 2"/><br/>
<input type="submit"/>
</form>