jQuery Validator Minimum Required Words

て烟熏妆下的殇ゞ 提交于 2020-01-02 08:52:27

问题


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

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.


回答1:


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.

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']
}


来源:https://stackoverflow.com/questions/19233901/jquery-validator-minimum-required-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!