Steven
Steven

Reputation: 25314

How to get the number of words in Jquery form validation plugin?

It is tag input box validation.A poster can combine multiple words into single-words, space is used to separate tags. I use Jquery form validation plugin to validate the form. I need to add a customized method to validate the tag input box. This is the code:

 $.validator.addMethod("tagcheck", function(value, element) { 
     return value && value.split(" ").length < 4;

    }, "Please input at most 3 tags.");

But what if there are two spaces between two adjacent words?

Upvotes: 0

Views: 1028

Answers (1)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827852

You can use a regular expression to split your string:

$.validator.addMethod("tagcheck", function(value, element) { 
  return value && value.split(/\s+/).length < 4;
}, "Please input at most 3 tags.");

\s+ Will match one or more white space characters, including space, tab, form feed, line feed.

Upvotes: 3

Related Questions