如何验证每个单词中的字符数?

How to validate the number of characters in each word?

这是输入的样子:

<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 autocomplete.

如您所见,它是由逗号(数据分隔符)分隔的标签。问题是 jquery validation plugin 无法读取单个标签的输入,它只查看字符总数。这是我的代码:

$('form#dropform3').validate({
  errorElement: "div",
  rules: { 
    'photo[tag_list]':          {required: false, maxlength: 20}
  },
});

因此,如果输入超过 20 个字符,则会 returns 出错并完全忽略数据分隔符。下面returns一个错误:

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.");

The problem is that jquery validation plugin cannot read the input for individual tags, it just looks at the total number of characters.

maxlength方法只查看字段中的字符总数。它没有做任何其他事情。

Quoting the docs: "Makes the element require a given maximum length"

如果您想根据定界符计算每个单词中的字符数,那么您需要为 jQuery 验证编写自定义规则。

使用 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 使用 "OR" 运算符在逻辑上将 this.optional(element) 与函数的结果进行比较。

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.");

演示:jsfiddle.net/y27v7vgc/