-1

I have a situation where angular validation sees an email as valid although it's not. The condition that that validation sees valid is example@domain Are there situations where this is an acceptable address?

<div class="form-group" ng-class="{ 'has-error': clientForm.email.$dirty && clientForm.email.$invalid, 'has-success': clientForm.email.$valid }">
        <label>Email</label>
        <span class="text-danger" ng-show="clientForm.email.$error.required">Email is required.</span>
        <span class="text-danger" ng-show="clientForm.email.$error.email">Invalid email address.</span>
        <input type="email" name="email" class="form-control input-sm" ng-model="client.email" required />
      </div>
ctilley79
  • 2,151
  • 3
  • 31
  • 64
  • this isn't Angular validation, this is the HTML5 `email` input type, and validation is dependent on browser support. – Claies Mar 15 '15 at 21:27
  • It is angular validation. But html5 could be overriding it since I forgot the 'novalidate' option. I'll see. – ctilley79 Mar 16 '15 at 01:07

1 Answers1

2

You can use a custom directive to validate it however you desire. Here's an example.

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
  $scope.client = {};
})
.directive('validEmail', function(emailRegex) {
  return {
    require: 'ngModel',
    link: function($scope, $element, $attrs, ngModel) {
      ngModel.$validators.validEmail = function(val) {
        if (!val) { return true; }
        return emailRegex.test(val);
      };
    }
  };
})
.value('emailRegex', /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<form ng-app="myApp" ng-controller="myCtrl" name="form">
  <label>Email</label>
  <span class="text-danger" ng-show="form.email.$error.required">Email is required.</span>
  <span class="text-danger" ng-show="form.email.$error.validEmail">Invalid email address.</span>
  <input type="text" name="email" ng-model="client.email" required valid-email/>
</form>

However, you should know that validating emails with RegEx is a lot more complicated than you'd ever want to know. Read this.

m59
  • 43,214
  • 14
  • 119
  • 136
  • 1
    Your regex was too short so I used the regex for RFC822 email addresses in the link provided. only 6.2 kb – ctilley79 Mar 16 '15 at 16:42