Is there an ng-model and input type email bug?

All we need is an easy explanation of the problem, so here it is.

Is there something special going on with input type=”email” and ng-model attribute?
If the input is email, then the model doesnt update.
If I change the input type to text, number or date it updates correctly.

Bug or some special magic email validation behavior that I dont understand?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

It does some validation on then input, so you need to have entered a valid email address before it is bound to the model.

This is the regex that is used:

/^[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/

Basically you need to input an address that is at least [email protected]

Method 2

It’s not a bug, it’s only update when we type correct email address format for email validation.
Add this attribute ng-model-options="{'allowInvalid': true}" to allow invalid email input.

Method 3

A complement, you can use properties on you form to see if your email is valid, like this :

HTML:

<form name="myForm" ng-submit="submit()">
    <input type="email" ng-model="email1" name="email1" />
</form>

Javascript:

//[formName].[inputFieldName].property 
myForm.email1.$pristine;
// Boolean. True if the user has not yet modified the form.
myForm.email1.$dirty
// Boolean. True if the user has already modified the form.
myForm.email1.$valid
// Boolean.True if the the form passes the validation.
myForm.email1.$invalid
// Boolean. True if the the form doesn't pass the validation.
myForm.email1.$error

Reference

Method 4

Starting from Angular 1.3, you can easily overwrite the ’email’ validator and make it always return true.

angular
  .module('myApp', [])
  .controller('MainController', function() {
    this.email = '';
  })
  .directive('noEmailValidation', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, elm, attr, ctrl) {
        ctrl.$validators['email'] = function() {
          return true;
        };
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<div ng-app="myApp">
  <form ng-controller="MainController as main">
    <div>Email: {{main.email}}</div>
    <input type="email" ng-model="main.email" no-email-validation>
  </form>
</div>

Enjoy.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply