【问题标题】:AngularJS Email validation inconsistencyAngularJS电子邮件验证不一致
【发布时间】:2015-05-17 21:49:05
【问题描述】:

我有一种情况,角度验证认为电子邮件是有效的,尽管它不是。该验证认为有效的条件是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>

【问题讨论】:

  • 这不是 Angular 验证,这是 HTML5 email 输入类型,验证取决于浏览器支持。
  • 这是角度验证。但是 html5 可能会覆盖它,因为我忘记了“novalidate”选项。我会看到的。

标签: angularjs validation email-validation


【解决方案1】:

您可以根据需要使用自定义指令来验证它。这是一个例子。

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>

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

【讨论】:

  • 您的正则表达式太短,所以我在提供的链接中使用了 RFC822 电子邮件地址的正则表达式。只有 6.2 kb
猜你喜欢
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2021-08-22
相关资源
最近更新 更多