我正在寻找一种使用 jQuery 验证某些输入文本区域的方法 - 不幸的是,尽管 jQuery 验证器插件很棒,但它缺乏验证(据我所知)“最少所需单词”。我没有携带代码(我将在早上编辑),但我编写了一个函数来计算输入中的单词数,但这并不像插件提供的那样进行干净的验证。
我还研究了 word-and-character-count.js,但这也没有提供提交表单的最低字数。
编辑:我提供的答案是一个自定义验证器方法——如果有人知道任何更干净的方法,甚至是一个易于使用的插件,请告诉我。
获取实时字数的函数,不包括末尾的空格(简单地分割就会计数)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']
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)