Search code examples
javascriptangularjsvalidationionic-frameworkng-messages

How to fire ng-messages on blur?


THE SITUATION:

I have many forms in my angular app and i need an effective error messages system. I find ngMessages useful.

But i would like that the error messages appears only when the user blur out of a field, in order to be less 'aggressive'.

ATTEMPT:

Attempt using debouncing at 1000ms

<label class="item item-input">
    <span class="input-label"> Email alternative </span>
    <input type="email" name="email_alternative" ng-model="profile_edited.email2" ng-model-options="{ debounce: 1000 }">
</label>

<!-- Error messages for ALTERNATIVE EMAIL  -->
<label class="item item-input" ng-show="profile_edit_form.email_alternative.$error.email">
    <div class="form-errors" ng-messages="profile_edit_form.email_alternative.$error" role="alert" ng-if='profile_edit_form.email_alternative.$dirty'>
        <div class="form-error" ng-message="email">Your email address is invalid</div>
    </div>
</label>

In this way it will properly appears the error message if the user is not typing anything for one second. Is the closest i get to what i want.

But sometimes for some users it may take a bit more than 1 second to type the character @. The error message may then suddenly appear and confuse the user.

But if i set the debouncing time 2 or 3 seconds is way too much. It may appear when the user is already writing in another field.

I need that the error messages fire ONLY AFTER the user blur out of the field.

THE QUESTION:

How can i fire ngMessages on blur?


Solution

  • $dirty will evaluate to true if the text is changed in the input box. To check for the blur you can use the $touched property of the input field.

    Checkout the forms documentation to see all form (input) properties: https://docs.angularjs.org/guide/forms