这是输入的样子:
<input data-delimiter=", " data-auto-focus="true" placeholder=""
data-autocomplete="/photos/autocomplete_tag_name" data-id-element="#tag_element"
type="text" value="" name="photo[tag_list]" id="photo_tag_list"
class="ui-autocomplete-input error" autocomplete="off" aria-describedby="photo_tag_list-error"
aria-invalid="true">
如您所见,它是用逗号(数据分隔符)分隔的标签。问题是jquery validation plugin无法读取单个标签的输入,它只是查看字符总数。这是我的代码:
$('form#dropform3').validate({
errorElement: "div",
rules: {
'photo[tag_list]': {required: false, maxlength: 20}
},
});
因此,如果输入超过20个字符,则返回错误并完全忽略数据分隔符。以下内容返回错误:
beach, hot, picnic, watermelon, swimming, summer,
因为它超过二十个字符。
修改
'photo[tag_list]': {required: false, taglength: true}
jQuery.validator.addMethod("taglength", function(value, element, params) {
var taggings = value.split(/[,]/);
for (var i = 0, limit = taggings.length; i < limit; i++) {
value = taggings[i];
if(value.length > 20) {
return false;
}
else {
return true;
}
}
}, "One of your tags is greater than 20 characters.");
答案 0 :(得分:1)
问题是jquery验证插件无法读取单个标签的输入,它只是查看字符总数。
maxlength
方法仅查看字段中的字符总数。它没有做任何其他事情。
Quoting the docs:&#34;使元素需要给定的最大长度&#34;
如果要根据分隔符计算每个单词中的字符数,那么您需要为jQuery Validate编写自定义规则。
使用the addMethod()
method创建自定义规则。
示例:
jQuery.validator.addMethod("taglength", function(value, element, param) {
// your function to count characters in each word goes in here
// use any of these arguments in your function: value, element, params
// value => the present value of the field being tested
// element => the present field being tested
// param => the parameter(s) passed in when you declare the rule.
// example: // taglength: 20 // param would be 20
// return true // if the field passes validation
// return false // if the field fails validation and the message below will display
}, "One of your tags is greater than {0} characters."));
The online examples在逻辑上将this.optional(element)
与函数的结果进行比较,使用&#34; OR&#34;运营商。
return this.optional(element) || { your result (true or false) };
否则,您的自定义规则将始终强制该字段。这可能适用于您的情况,但是,通常如果您希望字段为必填项,您也会应用required
规则。
要查看更多自定义方法示例,请查看the additional-methods.js
file的来源。
根据OP的尝试进行编辑:
在.validate()
内:
'photo[tag_list]': {
taglength: 20
}
自定义方法:
jQuery.validator.addMethod("taglength", function(value, element, param) {
var i,
result = true,
taggings = value.split(/[,]/);
for (i = 0; i < taggings.length; i++) {
if (taggings[i].length > param) {
result = false;
}
}
return this.optional(element) || result;
}, "One of your tags is greater than {0} characters.");