AngularJS custom form validation error message

angularjsangularjs-directive

Is there any way to pass an error message in custom form validation?

E.g. I have a directive that checks a username. There are three possible outcomes:

  1. It is valid
  2. It is invalid because it isn't a good username ("this.is-invalid")
  3. It is invalid because it is already in use

I have a directive like (simplified pseudo-html):

<input type="text" namecheck></input><span ng-show="name.$error.namecheck">You had an error {{ error }}</span>

And in my custom directive, I can do

// check for a conflict and valid name here
ngModel.$setValidity("namecheck",false);

But how do I pass an error message that indicates if the problem was a conflict or invalid name? Is there anything like ngModel.$setValidityErrorMessage() ?

Best Answer

As I wrote in the comments, I just figured it out. I just need to use different validity flags. Nothing says that I have to use the same key in $setValidity() as the name of the directive!

<span ng-show="name.$error.nameinvalid">This is not a valid username, it must be alphanmueric</span>
<span ng-show="name.$error.nametaken">Sorry, the username {{ name }} is already taken</span>

And in the directive

// if I got a 409
ngModel.$setValidity("nametaken",false);
// if I got a 400
ngModel.$setValidity("nameinvalid",false);

The name of the $error is the error message!