Mike Sav
Mike Sav

Reputation: 15291

AngularJS Custom validation - set a form item to invalid in the Controller

I wish to quickly introduce some functionality to my app where if a certain validation criteria isn't met (for example a word count of miniumum 20) we set a form item to invalid. I am unsure if I should use a filter, directive or simply do the logic in the controller, for example here is my form and what I have done so far:

<form name="registerForm" data-ng-submit="publishReview(review)" novalidate       autocomplete="off">
   <textarea name="review-text" data-ng-model="review.description" required></textarea>

<!-- more stuff -->
</form>

Now I have added the following to my controller:

$scope.$watch('review.description', function(newVal) {

      if(typeof(newVal) !== 'undefined' && newVal.match(/\w+/g) !== null && newVal.match(/\w+/g).length > 20) {

      // set to true

      } else {

      // set to false
      }

})

;

Now I am unsure how to set the item to false/invalid, I'm currently looking through the AngularJS docs on the NgModelController here https://docs.angularjs.org/api/ng/type/ngModel.NgModelController , and at the same time I feel uneasy putting this in my controller? As if it was bad practice? Although in the controller I can easily set the value of ng-show/hide conditions associated with the validation logic.

Any thoughts, ideas, opinions and answers appreciated.

Upvotes: 0

Views: 1634

Answers (2)

Mike Sav
Mike Sav

Reputation: 15291

I decided to go with a directive in the end...

angular.module('ecQDesktopApp')
    .directive('wordCount', function () {

        return {
            restrict: 'A', // only activate on element attribute
            require: '?ngModel', // get a hold of NgModelController
            link: function(scope, element, attrs, ngModel) {

                // do nothing if no ng-model
                if(!ngModel) {
                    return;
                }

                // Listen for change events to enable binding
                element.bind('blur keydown keyup change', function() {

                    if(typeof(element[0].value) !== 'undefined' && element[0].value.match(/\w+/g) !== null && element[0].value.match(/\w+/g).length > 20 && element[0].value.match(/[0-9a-zA-Z]/g).length > 20) {
                        // set to true
                        ngModel.$setValidity('wordcount', true)
                    } else {
                        ngModel.$setValidity('wordcount', false)
                    }


                });

            }
        };
})
;

Upvotes: 0

Chrissx
Chrissx

Reputation: 357

This is nice tutorial to learn how to validate forms and others stuff in Angular JS

Upvotes: 1

Related Questions