如何使用jQuery验证检查确切的长度? [英] How can I check for exact length using jQuery Validation?
本文介绍了如何使用jQuery验证检查确切的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 jQuery Validation插件来验证表单,您如何确认字符串正确X个字符长?
Using the jQuery Validation plugin to validate forms, how would you confirm that a string is exactly X characters long?
推荐答案
由于(当前)没有内置方法,因此您需要添加自己的方法.这将起作用:
Since there is (currently) no built-in method for this, you'd need to add your own method. This would work:
jQuery.validator.addMethod("exactlength", function(value, element, param) {
return this.optional(element) || value.length == param;
}, $.validator.format("Please enter exactly {0} characters."));
然后可以这样使用:
$("#formtovalidate").validate({
rules: {
somefield: {
exactlength: 10
}
});
更新-工作原理
有人问我这是怎么回事.我不知道所有细节.我在以前存在的方法上对此方法进行了建模.但是,这是我最好的解释.
Update - How it Works
I've been asked how this works. I don't know all the details; I modeled this method on previously existing ones. However, this is my best attempt to explain it.
- 该函数接受
value
,element
和param
.-
value
是在要验证的字段中输入的值 -
element
是字段本身 -
param
是规则类型和冒号之后的任何内容.在上面的示例中,它是exactlength: 10
中的10
- The function takes in
value
,element
, andparam
.value
is the value entered in the field being validatedelement
is the field itselfparam
is whatever comes after the rule type and colon. In the example above, it's the 10 inexactlength: 10
-
||
运算符的意思是'评估此项目的左边.如果为true,则返回true.如果没有,请尝试右边的一个.如果为true,则返回true.否则,返回false.- 左边的项目是
this.optional(element)
.如果您的规则中不需要该元素,那么它将返回true,验证也将返回true.意思是如果我不告诉你该字段是必填项,那么我不在乎它是否有效." - 如果需要该字段,我们将移至
||
的右侧.这是实际的验证测试.它将字段输入的长度与您指定的长度进行比较.如果它们相同,则返回true,该方法返回true,并通过验证.否则,验证将失败.
- The
||
operator means 'evaluate the item left of this. If it's true, return true. If not, try the one on the right. If it's true, return true. Otherwise, return false.'- The item on the left is
this.optional(element)
. If the element is not required in your rules, this will return true, and so will the validation. Which means 'If I don't tell you that this field is required, I don't care whether it validates.' - If the field is required, we move to the right side of the
||
. This is the actual validation test. It compares the length of the field's input with the length you specified it should be. If they are the same, it returns true, the method returns true, and validation passes. Otherwise, validation fails.
就是这样.要获得更多帮助,请参见文档,尤其是有关
That's about it. For further help, see the documentation, particularly the part about custom validation methods.
这篇关于如何使用jQuery验证检查确切的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- The item on the left is
- 左边的项目是
-
查看全文