0
votes

I have a form with a field, and when that element has ng:invalid I am showing another (which is a tooltip) that has an error message.

However, I need to have that tooltip display different messages based on WHY the field isn't valid. For example:

  • If the user didn't enter ANY value, it should display "Required"
  • If the user didn't enter a valid email address, it should display "Please enter a vaild email address"
  • If the user entered an email address that exists (in a local array, say) then it should display a different message .. and so on.

Since ng:invalid would be set even if one of the rules fail, I need a way to differentiate between the rules and idenify the one that failed, and then set the HTML for the tooltip based on that.

What's the "angular way" to do this?

EDIT: I was able to solve part of this using ng-invalid-required. But the question is still open, for multiple other rules on the same field.

1

1 Answers

1
votes

By default AngularJS exposes an $error object that you can use to get more information about the error. See the following example:

<form name="userForm">
<input id="userEmail" name="userEmail" type="email" data-ng-model="userEmail">

<div class="alert alert-errors" data-ng-show="userForm.userEmail.&dirty && userForm.userEmail.&invalid">
  <p data-ng-show="userForm.userEmail.$error.required">Email is required.</p>
  <p data-ng-show="userForm.userEmail.$error.email">Please enter a valid email address.</p>
<div>
</form>

Angular only covers some scenarios out of the box. To cover your final requirement, you will need to write a custom validation. This should get you headed in the right direction: https://docs.angularjs.org/guide/forms