3

我正在寻找一种使用 jQuery 验证某些输入文本区域的方法——不幸的是,与 jQuery 验证器插件一样棒,它缺乏验证(据我所知)“最少需要的单词”。我没有代码(我会在早上编辑),但我写了一个函数来计算你输入的单词,但这不像插件提供的那样干净的验证。

我还查看了 word-and-character-count.js,但这也没有提供提交表单的最低字数。

编辑:我提供的答案是自定义验证器方法——如果有人知道任何更简洁的方法甚至是易于使用的插件,请告诉我。

4

1 回答 1

12

获取实时字数的函数,不包括末尾的空格(简单地拆分会将say word(注意末尾的空格)计为2个单词。

function getWordCount(wordString) {
  var words = wordString.split(" ");
  words = words.filter(function(words) { 
    return words.length > 0
  }).length;
  return words;
}

//add the custom validation method
jQuery.validator.addMethod("wordCount",
   function(value, element, params) {
      var count = getWordCount(value);
      if(count >= params[0]) {
         return true;
      }
   },
   jQuery.validator.format("A minimum of {0} words is required here.")
);

//call the validator
selector:
{
    required: true,
    wordCount: ['30']
}
于 2013-10-07T20:17:58.047 回答