JQuery 验证插件最大长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18373865/
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 validation plugin maxlength?
提问by user755806
I am using JQuery validation plugin. I want to specify maxlength
for one of the fields.It can be specified as below.
我正在使用 JQuery 验证插件。我想maxlength
为其中一个字段指定。它可以指定如下。
rules: {
Message: {
required: false,
maxLength: 200
}
}
But instead of defining the rules externally, i want to specify the rules inside html input code
但不是在外部定义规则,我想在 html 输入代码中指定规则
Similar to :
相似 :
<input type="text" name="AssistanPhone" value="" class="required" />
In above example "required" is specified through class. Similarly how can i specifiy maxlength which can be recognized by jquery plugin and gives error message if length exceeds?
在上面的例子中,“required”是通过类指定的。同样,我如何指定 jquery 插件可以识别的 maxlength 并在长度超过时给出错误消息?
Thanks!
谢谢!
回答by Suresh Atta
Not capital L
its l
不是资本L
其l
Ex:
前任:
$( "#myform" ).validate({
rules: {
field: {
required: true,
maxlength: 200
}
}
});
回答by Arun P Johny
回答by Tominator
I updated the javascript code of the validator myself (so I'm stuck with my version 1.8.1 now instead of upgrading), but here's what I did (around line 767):
我自己更新了验证器的 javascript 代码(所以我现在坚持使用 1.8.1 版而不是升级),但这是我所做的(大约第 767 行):
classRules: function(element) {
var rules = {};
var classes = $(element).attr('class');
classes && $.each(classes.split(' '), function() {
if (this in $.validator.classRuleSettings) {
$.extend(rules, $.validator.classRuleSettings[this]);
}
if (this.toLowerCase().lastIndexOf('maxlength-', 0) === 0) { // starts with
var x = parseInt(this.substring(10)); // take number after 'maxlength-'
$.extend(rules, {maxlength: x});
}
});
return rules;
},
I added the extra if-test for "maxlength-", so now I can add a class like "maxlength-10" to limit to 10. Of course I could also add minlength and so on.
我为“maxlength-”添加了额外的if-test,所以现在我可以添加一个像“maxlength-10”这样的类来限制为10。当然我也可以添加minlength等等。
回答by Tayyeb
$("#FormID").validate({
rules: {
PriorityDDL: {
required: true
},
Title: {
required: true
},
Text: {
required: true,
maxlength: 300
},
date: {
required: true
},
reportfile: {
required: true
}
},
messages: {
PriorityDDL: {
required: "Please select priority"
},
Title: {
required: "Please enter title"
},
Text: {
required: "Please enter message",
maxlength:"maxLength is 300 characters"
},
date: {
required: "Please select date"
},
reportfile: {
required: "Please select file"
}
}
});