如何使用 jQuery 验证检查确切长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1229141/
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 can I check for exact length using jQuery Validation?
提问by Nathan Long
Using the jQuery Validation pluginto validate forms, how would you confirm that a string is exactly X characters long?
使用jQuery Validation 插件来验证表单,您如何确认一个字符串的长度正好是 X 个字符?
回答by Nathan 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."));
Which could then be used like this:
然后可以这样使用:
$("#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.
有人问我这是如何工作的。我不知道所有的细节;我在以前存在的方法上模拟了这种方法。然而,这是我最好的解释。
- 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
- The next line is a
return
statement. This will give the final verdict of the validation method back to the code that called it. Any validation method that returnstrue
is saying 'this field passes validation!' It will return the value of the line it's on. - The
return
is followed by two declarations, separated by an 'or' operator (||
).- 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.
- The item on the left is
- The
- 该函数中
value
,element
和param
。value
是在要验证的字段中输入的值element
是字段本身param
是规则类型和冒号之后的任何内容。在上面的例子中,它是 10exactlength: 10
- 下一行是一个
return
声明。这会将验证方法的最终判定返回给调用它的代码。任何返回的验证方法true
都说“此字段通过验证!” 它将返回它所在行的值。 - 的
return
后面是两个声明,通过“或”运算符分开的(||
)。- 该
||
操作装置“评估留下的这个项目。如果为真,则返回真。如果没有,请尝试右侧的那个。如果为真,则返回真。否则,返回 false。- 左边的项目是
this.optional(element)
。如果您的规则中不需要该元素,这将返回 true,验证也是如此。这意味着“如果我不告诉你这个字段是必需的,我不在乎它是否有效。” - 如果该字段是必需的,我们将移至
||
. 这是实际的验证测试。它将字段输入的长度与您指定的长度进行比较。如果它们相同,则返回 true,该方法返回 true,并且验证通过。否则,验证失败。
- 左边的项目是
- 该
That's about it. For further help, see the documentation, particularly the part about custom validation methods.
回答by Igor
example:
例子:
rules : {
"someFieldName":{digits:true,minlength:20,maxlength:20}
}
回答by Lars Gyrup Brink Nielsen
You could also make the existing rangelength
method support exact range by supplying a dynamic message like this:
您还可以rangelength
通过提供如下动态消息使现有方法支持精确范围:
$.extend($.validator.messages, {
rangelength: function(args, inputElement) {
var isExactRange, min, max;
// Cast arguments as numbers
min = Number(args[0]);
max = Number(args[1]);
isExactRange = min === max;
if (isExactRange) {
return 'Please enter exactly ' + min + ' characters.';
}
return 'Please enter between ' + min + ' and ' + max + ' characters.';
}
);
As can be seen, you can generate messages on the fly based on the arguments passed to the validation methods. Message callbacks are passed the validation method arguments as their first argument, and the input element being validated as their second argument.
可以看出,您可以根据传递给验证方法的参数动态生成消息。消息回调将验证方法参数作为它们的第一个参数传递,并将被验证的输入元素作为它们的第二个参数传递。
This makes it possible to return one message when a exact range is specified, but another if upper and lower bounds are not the same.
这使得可以在指定确切范围时返回一条消息,但如果上限和下限不同,则返回另一条消息。
To fallback to the default rangelength
message, replace
要回退到默认rangelength
消息,请替换
'Please enter between ' + min + ' and ' + max + ' characters.'
with
和
$.validator.messages.rangelength
It would be nice if the official documentation would be updated, as it is difficult to navigate in and does not describe all functionalities of the plugin.
如果官方文档能更新就好了,因为它很难导航并且没有描述插件的所有功能。
回答by Ted Avery
The easiest way is to use the existing validation methods via data attributes, then just set your own validation message for clarity.
最简单的方法是通过数据属性使用现有的验证方法,然后为了清晰起见,只需设置您自己的验证消息。
<input data-rule-minlength="8" data-rule-maxlength="8" data-msg-minlength="Exactly 8 characters please" data-msg-maxlength="Exactly 8 characters please">