Niranjan Godbole Niranjan Godbole - 1 month ago 15
AngularJS Question

Angular js email validation not working for domain name

Hi I am developing angularjs application in which i am doing validation for email id. Whenever i enter test@test error message should come. but it is not working.

Below is my code.

<div class="inputblock with-icon mail" ng-class="{ 'has-error' : ((form.$submitted && form.email.$invalid)|| (form.email.$invalid && form.email.$dirty))}">
<label class="inputblock-label" ng-show="user.email">{{ 'Email' | translate }}</label>
<span class="input-icon"><img src="images/mail-icon.png"></span>
<div>
<span class="ang-error" style="color:#fff" ng-show="form.email.$dirty && form.email.$invalid">
<span ng-show="form.email.$error.required && form.email.$dirty">* {{'Required' | translate}}</span>
<span style="color:#fff" ng-show="form.email.$error.email">{{'Invalid EmailId' | translate}}</span>
</span>
</div>
<input type="email"
class="with-icon"
ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/"
placeholder="{{ 'Email' | translate }}"
ng-model="user.email"
required=""
name="email"
my-maxlength="50">
</div>


Whenever i enter test@test i can see below code in browser

<input type="email" class="with-icon ng-dirty ng-valid-required ng-invalid ng-invalid-pattern ng-valid-email ng-touched" ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" placeholder="Email" ng-model="user.email" required="" name="email" my-maxlength="50" ng-trim="True">


Below is the screen shot of field when i enter test@test
enter image description here

Below is the screen shot when i enter test@
enter image description here

May i know how can i fix the above error? any help would be appreciated. Thank you

Answer Source

You can try this:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;
    $scope.model = "test@test";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <form name="form">
         <input type="text" ng-model="model" id="input" name="input" ng-pattern="emailPattern" /><br>
         <p>input valid? = {{form.input.$valid}}</p>
  </form>
</div>