简体   繁体   English

jQuery Validator最小必需字

[英]jQuery Validator Minimum Required Words

I'm looking for a way to validate some input textareas using jQuery -- unfortunately as awesome as the jQuery validator plugin is, it lacks the validation (to my knowledge) "minimum required words". 我正在寻找一种方法来使用jQuery验证一些输入textareas - 不幸的是,因为jQuery验证器插件很棒,它缺乏验证(据我所知)“最低要求的单词”。 I don't have the code with me (I'll edit in the morning), but I wrote a function that counts the words in your input, but that wasn't clean validation like the plugin provides. 我没有代码(我早上会编辑),但是我编写了一个函数来计算输入中的单词,但这不是像插件提供的那样干净的验证。

I also looked into word-and-character-count.js, but that also does not provide a minimum word count in order to submit the form. 我也查看了word-and-character-count.js,但是为了提交表单,这也没有提供最小字数。

Edit: the answer I provided is a custom validator method -- if anybody knows any cleaner methods or even an easy to use plugin, please let me know. 编辑:我提供的答案是一个自定义验证方法 - 如果有人知道任何更清洁的方法,甚至一个易于使用的插件,请告诉我。

Function to get the live word count, excluding the spaces at the end (simply splitting will count say word (note the space at the end) as 2 words. 获取实时字数的功能,不包括末尾的空格(简单地分割将计算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']
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM