Restricted validators names in Angular

Issue

I’ve created custom validator and attached it to the input element’s model like:

ngModel.$validators.required = function (value) {
  return !!value;
}

And it does not work – function is not even called. However renaming it from required to alsoRequired – it is called properly.

Does Angular have some restrictions about validators naming ?

Solution

There isn’t enough code to understand exactly what is going on, but I could guess where your mistake is:

ngModel.$validators is set by any directive that decides to set it. For example, an input directive with type="email" sets $validators.email; ng-required directive sets $validators.required, and so on.

You may have ng-model set on a custom directive or even on <input type="text">, which on its own doesn’t register a validator.

Custom directives, like yours, can register a validator:

link: function(scope, element, attrs, ngModel){
  ngModel.$validators.required = function (value) {
    console.log(value); // this will fire if parsers do not return undefined
    return !!value;
  };
})

And if set in combination with ng-model, should work fine:

<input type="email" ng-model="foo" my-dir>

http://plnkr.co/edit/1oQGRWZ0kWlV6Q7WjvrY?p=preview

To answer your question, the likely reason why your $validators.required function is not called is because you have another directive that overwrites this value – for example, ng-required.

Answered By – New Dev

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.