添加jQuery验证方法时,this.optional(element)会做什么? [英] What does this.optional(element) do when adding a jQuery validation method?
问题描述
请参阅文件:
https://jqueryvalidation.org/ jQuery.validator.addMethod /
我想知道 this.optional(element)
的作用。我创建了两个表单进行测试:
Form1 和 Form2 - 其中一个 this.optional(element)
,另一个没有它。从理论上讲,根据安德鲁·惠特克对这个答案的一些评论:
全部
this.optional
does表示如果该字段是可选的,则返回true,如果它为空
和
this .optional
check主要检查字段是否为空,然后评估它是否符合规则。
但是在实际操作中,我发现 Form1 和 Form2 的工作。请帮助我理解行动上的差异。
确定...因此,在您的示例中,形成。它有一个占位符值,或者是一个电子邮件地址的尝试。如果元素为空并且不是必需的,那么 this.optional(element)
的全部要点立即返回true。
$ b $如果你有这两个方法:
$ p $ j code jQuery.validator.addMethod(BOB,function(value,元素){
return this.optional(element)||
element.value ==='BOB';
},'您没有输入BOB');
jQuery.validator.addMethod(mustbeBOB,function(value,element){
return element.value ==='BOB';
},'您没有输入BOB');
添加一个所需的BOB类
应该是与输入 mustbeBOB
类相同。把它比作一个 BOB
类,它允许空白或BOB,而类 mustbeBOB
这只会通过 BOB
值的验证,空白将失败。这是否更有意义?
Please see the documentation:
https://jqueryvalidation.org/jQuery.validator.addMethod/
I wonder what this.optional(element)
does. I created two forms to test:
Form1 and Form2 — one with this.optional(element)
and the other without it. Theoretically speaking and according to a couple of comments on this answer by Andrew Whitaker:
all
this.optional
does is say "if the field is optional, return true if it is blank"
and
The
this.optional
check is basically checking to see if the field is blank or not before evaluating whether or not it meets the rule.
But in action I see no difference in how Form1 and Form2 work. Please help me understand the difference in action.
OK... so in your examples, the field is never blank in either form. Either it has a placeholder value, or an attempt at an email address. The whole point of this.optional(element)
is to immediately return true if the element is blank AND it is not required.
So if you had these two methods:
jQuery.validator.addMethod("BOB", function (value, element) {
return this.optional(element) ||
element.value === 'BOB';
}, 'You did not enter BOB');
jQuery.validator.addMethod("mustbeBOB", function (value, element) {
return element.value === 'BOB';
}, 'You did not enter BOB');
Adding a class of BOB required
would be the same as entering a class of mustbeBOB
. Compare that to having a class of BOB
which would allow for a blank or "BOB", vs a class of mustbeBOB
which will only pass validation with a value of BOB
, blank would fail. Does that make more sense?
这篇关于添加jQuery验证方法时,this.optional(element)会做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!