jenryb
jenryb

Reputation: 2117

Custom validation as a function in Angular

In Angular, I am trying to validate a value of a field on blur. I have a list of customers, and I want to check if the model value in the field is in my list of customers. If not, I want to set the validity to false.

I know that ng-model-options="{updateOn: 'blur'} exists, however, I can't use this because the field is a typeahead so it must update based on the model. The validation is what needs to happen on blur.

The answer seems to be:

  1. Write it as a function in the controller and use $setValidity just as you would in a directive. Use ng-blur to trigger the function in the input field.

    -However, I keep running into examples where a custom validation (make the field invalid if the model value does not match one in the list) is only written as a directive. Are there examples of custom validation written as a function?

  2. Write a directive that only triggers on blur.

However, I can't find examples that do either of these things.

Does anybody have an example of custom validation as a function OR a directive that only updates on blur of the field?

I found this link very helpful for custom validation but I still have the same problem with the difference between a function and a directive: How to add custom validation to an AngularJS form?

** My typeahead works, I do not need help getting uib-typeahead working but rather the accompanying custom validation

Upvotes: 1

Views: 159

Answers (1)

Alexander Kravets
Alexander Kravets

Reputation: 4395

Here the example of custom validation triggered on blur:

angular.module('myApp', [])
.directive('customValidation', function() {
    return {
        require: 'ngModel',
        link: function(scope, el, attrs, ngModel) {
            el.bind('blur', function(event) {
                scope.$apply(function() {
                    ngModel.$setValidity('customValidation', scope.name == 'test');
                });
            })
        }
    };
});

Plunk

Upvotes: 1

Related Questions