jQuery Validator Minimum Required Words

jQuery Validator Minimum Required Words

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.
1)

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

2) call the validator

$(document).ready(function(){
    $("#validateForm").validate({
        rules: {
            name1: {required: true,wordCount: [2, 1000]},
            name2: {required: true,wordCount: [2, 1000]}
        }
    });
});

Jayesh Patel
Author
Jayesh Patel

Jayesh Patel is a Professional Web Developer & Designer and the Founder of InCreativeWeb.

As a highly Creative Web/Graphic/UI Designer - Front End / PHP / WordPress / Shopify Developer, with 14+ years of experience, he also provide complete solution from SEO to Digital Marketing. The passion he has for his work, his dedication, and ability to make quick, decisive decisions set him apart from the rest.

His first priority is to create a website with Complete SEO + Speed Up + WordPress Security Code of standards.



Explore

Related Articles

11th April, 2024

W3 Total Cache: A Comprehensive Review & Guide for 2024

8th April, 2024

Top 10 Must-Have Web Design Resources and Tools for 2024

8th April, 2024

Unleash Accessibility Potential in Front-end Development