AngularJS电子邮件验证不一致

时间:2015-03-15 20:14:00

标签: angularjs validation email-validation

我有一种情况,即角度验证会将电子邮件视为有效,尽管不是。验证有效的条件是example@domain是否存在可接受的地址?

<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>

1 个答案:

答案 0 :(得分:2)

您可以根据需要使用自定义指令对其进行验证。这是一个例子。

&#13;
&#13;
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,}))$/)
;
&#13;
<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>
&#13;
&#13;
&#13;

但是,您应该知道使用RegEx验证电子邮件比您想知道的要复杂得多。 Read this.