jquery-validate - addMethod - 如何应用引用两个文本框的自定义规则?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8263535/
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
jquery-validate - addMethod - how to apply custom rule referencing two text boxes?
提问by shearichard
I'm using the jQuery validation pluginand I want make use of a custom method which takes two the values entered into two different textboxes into account when deciding if the situation is valid.
我正在使用jQuery 验证插件,并且我想使用一个自定义方法,该方法在确定情况是否有效时将输入到两个不同文本框中的两个值考虑在内。
I know about add methodand I've found an example ...
我知道add 方法,我找到了一个例子......
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.format("Please enter the correct value for {0} + {1}"));
... which references two elements but I'm not clear how to write a rule which would make use of a method such as this ?
...它引用了两个元素,但我不清楚如何编写使用这种方法的规则?
To make it easier to discuss imagine that I want to make use of this example method and I've got a form that looks like this ..
为了更容易讨论,假设我想使用这个示例方法,并且我有一个看起来像这样的表单..
<form id="TOTALSFORM" name="TOTALSFORM">
<label for="LHSOPERAND">Input 1</label>
<br />
<input type="text" name="LHSOPERAND" id="LHSOPERAND" class="required" />
<br />
<label for="RHSOPERAND">End</label>
<br />
<input type="text" name="RHSOPERAND" id="RHSOPERAND" class="required" />
<label for="TOTAL">End</label>
<br />
<input type="text" name="TOTAL" id="TOTAL" class="required" />
</form>
I've got other rules that I apply like this :
我还有其他规则可以这样应用:
$("#OPTREASON").rules("add", {
required: true,
min: 0,
messages: {
required: "Required input",
min: "Please select a Reason"
}
});
How can I do something similar to apply the example custom method shown so that 'TOTAL' is checked as being the sum of 'LHSOPERAND' and 'RHSOPERAND'.
我该如何做类似的事情来应用显示的示例自定义方法,以便将“TOTAL”检查为“LHSOPERAND”和“RHSOPERAND”的总和。
回答by dSquared
Try the following:
请尝试以下操作:
Create the Rule
创建规则
jQuery.validator.addMethod("checkTotal",function(value) {
total = parseFloat($('#LHSOPERAND').val()) + parseFloat($('#RHSOPERAND').val());
return total == parseFloat($('#TOTAL').val());
}, "Amounts do not add up!");
jQuery.validator.classRuleSettings.checkTotal = { checkTotal: true };
Input
输入
<input type="text" name="TOTAL" id="TOTAL" class="required checkTotal" />
Init Validation
初始化验证
$(document).ready(function() {
$("#TOTALSFORM").validate();
});
Fiddle here: http://jsfiddle.net/wTMv3/
在这里小提琴:http: //jsfiddle.net/wTMv3/