Friday, August 7, 2009

Counting Words, StringWordValidator

I was recently required to limit the number of words in a TextArea. It's easy to limit the number of characters by using the TextArea.maxChars property, but how do you restrict the number of words?

The way I solved this problem was to make a new class that extends mx.validators.StringValidator and adds the following properties:
  • maxWords - the maximum number of words allowed
  • minWords - the minimum number of words allowed
  • tooManyWordsError - the error string to be displayed when too many words are entered
  • tooFewWordsError - the error string when not enough words are entered
  • trim - trims the input string before the validation occurs

Here is the utility function I wrote for counting how many words are in a string:
    /**
     * Splits the text into words and returns the number of words found.
     * If the text is null or blank (trimmed) then 0 is returned.
     * The regular expression used is /\s+/g which splits the text into
     * words based on whitespace.
     */
    public static function countWords(txt:String):uint {
        var count:uint = 0;
        if (txt != null) {
            txt = StringUtil.trim(txt);
            if (txt.length > 0) {
                count = txt.split(/\s+/g).length;
            }
        }
        return count;
    }

And here is it in action (view source). The validator will run when the TextArea loses focus (that is the default behavior), so try typing in one word and then pressing tab. You can also adjust the minimum and maximum number of words allowed and the validation will be updated immediately.

  • StringWordValidator source
  • ErrorTipManager source (see previous blog post on Always showing error tips)

  • I also included the ResizableTextArea class too just for fun.

    No comments: