Reputation: 22425
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.
Upvotes: 3
Views: 7168
Reputation: 22425
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']
}
Upvotes: 14