如何添加“依赖项" jQuery Validation插件中的valueNotEquals规则的条件? [英] How to add a "depends" condition on valueNotEquals rule in jQuery Validation plugin?
问题描述
我在jQuery Validation插件中使用"depend",以便仅在特定情况下应用某些验证规则.这是我在某些情况下仅需要字段required
时使用的代码.
I use the "depend" in jQuery Validation plugin in order to apply some validation rules only in specific cases. This is the code I use to do it in case I want a field required
only under certain circumstances.
fieldA: {
required: {depends: function () {
return $('#FormName select[name="fieldB"]').val() === '10';
}}
}
如果我想使用valueNotEquals
规则,则语法如下:
In case I want to use the valueNotEquals
rule I have a syntax like this:
fieldA:
{valueNotEquals: "0"}
如果我想使用"depends",正确的语法是什么?两次尝试都给出了错误和语法错误.
If I want to use "depends", what is the right syntax? These two attempts gave error and syntax error.
温度1 (错误,因为我无法表明它不能等于什么值)
Attemp 1 (error for I could not indicate WHAT value it must not equals)
fieldA:
{valueNotEquals: {depends: function () {
return $('#QuestionarioForm select[name="lavoroMadre"]').val() === '10';}}
尝试2 (语法错误)
fieldA:
{valueNotEquals: "0" {depends: function () {
return $('#QuestionarioForm select[name="lavoroMadre"]').val() === '10';}}
推荐答案
您的代码:
fieldA:
{valueNotEquals: "0"}
引用标题:
如何在jQuery Validation插件中的valueNotEquals规则上添加依赖"条件?"
您的代码无法正常工作,因为jQuery Validate插件中没有称为valueNotEquals
的规则或方法.
Your code is not working because there is no such rule or method called valueNotEquals
in the jQuery Validate plugin.
已记录的规则和方法: http://jqueryvalidation.org/category/methods/
您必须使用 addMethod()
编写自己的自定义规则:>
jQuery.validator.addMethod("valueNotEquals", function(value, element, params) {
return this.optional(element) || (value != params[0]);
}, "Please specify a value that is not equal to {0}");
并声明规则:
fieldA: {
valueNotEquals: [0]
}
自定义方法的演示: http://jsfiddle.net/cF3p5/
现在您无需使用depends
.只需编辑此自定义函数,使其表现出所需的效果即可.也许更像这样...
Now you wouldn't need to use depends
. Simply edit this custom function so that it behaves as you want. Maybe something more like this...
jQuery.validator.addMethod("valueNotEquals", function(value, element, params) {
if ($('#QuestionarioForm select[name="lavoroMadre"]').val() === params[1]) {
return (value != params[0]);
} else {
return true;
}
}, "Please specify a value that is not equal to {0}");
并声明规则:
fieldA: {
valueNotEquals: [0, 10]
}
这篇关于如何添加“依赖项" jQuery Validation插件中的valueNotEquals规则的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!