Angularjs email validation fires too quickly?

Issue

I am trying to validate an email field in angularjs which looks like this:

<input type="email" ng-model="email" class="form-control" name="email" ng-required="true" placeholder="Email Address">
<span ng-show="loginForm.email.$touched && loginForm.email.$invalid">A valid email is required</span>

It all works as expected, but presents a horrible user experience due to the fact that the error message “A valid email is required” will show when the user types a “.” and then will hide when the user continues typing. Because email@email. is invalid but email@email.com is valid.

The problem is that the validation happens too quickly, before the user has finished typing.

I have tried to solve this by using the $touched flag, but it solves it only the first time the user enters the email. When they go back to correct the email they end up with the error message flicking when they type a “.” or a “-” in the domain name.

Has anyone solved this somehow?

Solution

You could make use of ng-model-options to specify when the model update should happen(and eventually the validation as well) on blur event by specifying ng-model-options="{updateOn:'blur'}". You can provide this at the app level as well so that it is applicable to every ng-models. This will cause the validation and model update to trigger when the user focus out of the input. It has debounce options as well.

 <input type="email" ng-model="email" class="form-control" name="email" 
        ng-required="true" ng-model-options="{updateOn:'blur'}" 
        placeholder="Email Address" />
  <span ng-show="loginForm.email.$touched && loginForm.email.$invalid">A valid email is required</span>
angular.module('app', []).controller('ctrl', function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <form name="loginForm">
    <input type="email" ng-model="email" class="form-control" name="email" ng-required="true" ng-model-options="{updateOn:'blur'}" placeholder="Email Address">
    <span ng-show="loginForm.email.$touched && loginForm.email.$invalid">A valid email is required</span>
    {{email}}
  </form>
</div>

Answered By – PSL

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.