AngularJS Custom Form Validation


Example

In some cases basic validation is not enough. Angular support custom validation adding validator functions to the $validators object on the ngModelController:

angular.module('app', [])
  .directive('myValidator', function() {
    return {
      // element must have ng-model attribute
      // or $validators does not work
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {
        ctrl.$validators.myValidator = function(modelValue, viewValue) {
            // validate viewValue with your custom logic
            var valid = (viewValue && viewValue.length > 0) || false;
            return valid; 
        };
      } 
    };

The validator is defined as a directive that require ngModel, so to apply the validator just add the custom directive to the input form control.

<form name="form">
  <input type="text" 
         ng-model="model" 
         name="model" 
         my-validator>
  <pre ng-bind="'my-validator returned: ' + form.model.$valid"></pre>
</form> 

And my-validator doesn't have to be applied on native form control. It can be any elements, as long as it as ng-model in its attributes. This is useful when you have some custom build ui component.

example