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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

Answers:

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]

Questions:
Answers:

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.

Questions:
Answers:

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

Questions:
Answers:

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.