jQuery Validator最小必需字 [英] jQuery Validator Minimum Required Words

查看:84
本文介绍了jQuery Validator最小必需字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用jQuery验证一些输入textareas的方法 - 不幸的是,jQuery验证器插件非常棒,它缺乏验证(据我所知)最低要求的单词。我没有代码(我早上会编辑),但是我编写了一个函数来计算输入中的单词,但这不是像插件提供的那样干净的验证。

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.

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

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.

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

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.

推荐答案

获取实时字数的功能,不包括末尾的空格(简单分割将计算为(注意空格最后)为2个单词。

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

这篇关于jQuery Validator最小必需字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆