1

I'm trying to validate my text area:

<form id="contact_form" name="contactform" ng-submit="submit(contactform)" role="form">
    <textarea class="form-control" id="Message" ng-model="formData.message" ng-trim="false" placeholder="Your message" required="required" rows="8"></textarea>
</form>

For max word count, so I added a filter :

app.filter('wordCounter', function () {
  return function (value) {
    if (value && typeof value === 'string') {
        return value.trim().split(/\s+/).length;
    } else {
        return 0;
    }
  };
});

And when this filter is met I print out an error :

<span class="help-block" ng-show="(formData.message|wordCounter) > 200">
  Max 200 words please!
</span>

But still when I check in my controller contactform.$valid is always true, how do I make form invalid if the filter wordcounter is more than 200?

1 Answer 1

2

You need to create a custom validation directive. With Angular 1.3 $validators it's very easy.

For example, simple one:

.directive('maxWords', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {
            ngModelController.$validators.maxWords = function(viewValue, modelValue) {
                if (!ngModelController.$isEmpty(modelValue)) {
                    return modelValue.trim().split(/\s+/).length <= attrs.maxWords;
                }
            };
        }
    };
});

Demo: http://jsfiddle.net/m3pp71o4/

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, that works! Another newbie question, can I put this directive somewhere on a application level or rootController, rather than specific controller so I can reuse it in other parts of the app
Yes, of course. You should define this directive in main application module and be able to use it everywhere. It doesn't depend on any specific controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.