59

我正在尝试使用 ng-pattern 指令验证 angularJs 中的电子邮件 id 字段。

但我是 AngularJs 的新手。用户输入错误的电子邮件 ID 后,我需要立即显示错误消息。

我下面的代码正在尝试解决。帮助我使用 ng-pattern 来获得正确的结果。

<script type="text/javascript" src="/Login/script/ang.js"></script>
<script type="text/javascript">
    function Ctrl($scope) {
        $scope.text = 'enter email';
        $scope.word = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
    }
</script>
    </head>
<body>
    <form name="myform" ng-controller="Ctrl">
        <input type="text" ng-pattern="word" name="email">
        <span class="error" ng-show="myform.email.$error.pattern">
            invalid email!
        </span>
        <input type="submit" value="submit">
    </form>
</body>
4

12 回答 12

66

如果要验证电子邮件,请使用 type="email" 而不是 type="text" 的输​​入。AngularJS 具有开箱即用的电子邮件验证功能,因此无需为此使用 ng-pattern。

以下是原始文档中的示例:

<script>
function Ctrl($scope) {
  $scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
  Email: <input type="email" name="input" ng-model="text" required>
  <br/>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
  <span class="error" ng-show="myForm.input.$error.email">
    Not valid email!</span>
  <br>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>

有关更多详细信息,请阅读此文档:https ://docs.angularjs.org/api/ng/input/input%5Bemail%5D

现场示例:http ://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info

升级版:

如果您对内置的电子邮件验证器不满意,并且想要使用自定义 RegExp 模式验证,则可以应用 ng-pattern 指令,根据文档,错误消息可以显示如下:

如果 ngModel.$viewValue 与 RegExp 不匹配,验证器会设置模式错误键

<script>
function Ctrl($scope) {
  $scope.text = 'me@example.com';
  $scope.emailFormat = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
  Email: <input type="email" name="input" ng-model="text" ng-pattern="emailFormat" required>
  <br/><br/>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!
  </span><br/>
  <span class="error" ng-show="myForm.input.$error.pattern">
    Not valid email!
  </span>
  <br><br>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.pattern = {{!!myForm.$error.pattern}}</tt><br/>
</form>

Plunker:https ://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview

于 2014-06-30T13:04:27.990 回答
54

有一个很好的例子如何处理这种修改内置验证器angulardocs的问题。我只添加了更严格的验证模式。

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (ctrl && ctrl.$validators.email) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

只需添加

<input type='email' validate-email name='email' id='email' ng-model='email' required>  
于 2015-02-10T11:59:33.820 回答
10

根据@scx 的回答,我为 GUI 创建了一个验证

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = EMAIL_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

并简单地添加:

css

.warning{
   border:1px solid red;
 }

html

<input type='email' validate-email name='email' id='email' ng-model='email' required>
于 2015-05-30T09:13:18.673 回答
6

这是使用正则表达式的 jQuery 电子邮件验证。如果您对 AngularJS 有所了解,也可以对 AngularJS 使用相同的概念。

var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

来源

于 2017-03-26T07:13:18.627 回答
3

Now, Angular 4 has email validator built-in https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://github.com/angular/angular/pull/13709

Just add email to the tag. For example

  <form #f="ngForm">
    <input type="email" ngModel name="email" required email>
    <button [disabled]="!f.valid">Submit</button>
    <p>Form State: {{f.valid?'VALID':'INVALID'}}</p>
  </form>
于 2017-04-17T05:38:53.317 回答
3

以下是电子邮件验证的完全限定模式。

<input type="text" pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]*\.([a-z]{2,4})$/" ng-model="emailid" name="emailid"/>

<div ng-message="pattern">Please enter valid email address</div>
于 2016-10-26T06:31:11.820 回答
3

您可以使用 ng-messages

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.min.js"></script>

包括模块

 angular.module("blank",['ngMessages']

在 HTML 中

<input type="email" name="email" class="form-control" placeholder="email" ng-model="email" required>
<div ng-messages="myForm.email.$error">
<div ng-message="required">This field is required</div>
<div ng-message="email">Your email address is invalid</div>
</div>
于 2016-07-19T15:42:42.797 回答
0

我尝试了@Joanna 的方法并在以下网站上进行了测试,但没有成功。

  1. https://regex101.com/
  2. https://www.regextester.com/
  3. https://regexr.com/

然后我将其修改为并且有效。

/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+
于 2017-11-18T18:57:18.367 回答
0

花一些时间让它为我工作。

要求:

单个或逗号分隔的电子邮件列表,域名以 name.surname@gmail.com 或 team-email@list.gmail.com 结尾

控制器:

$scope.email = {
   EMAIL_FORMAT:  /^\w+([\.-]?\w+)*@(list.)?gmail.com+((\s*)+,(\s*)+\w+([\.-]?\w+)*@(list.)?gmail.com)*$/,
   EMAIL_FORMAT_HELP: "format as 'your.name@gmail.com' or comma separated 'your.name@gmail.com, my.name@list.gmail.com'"
};

HTML:

<ng-form name="emailModal">
    <div class="form-group row mb-3">
        <label for="to" class="col-sm-2 text-right col-form-label">
            <span class="form-required">*</span>
            To
        </label>
        <div class="col-sm-9">
            <input class="form-control" id="to"
                   name="To"
                   ng-required="true"
                   ng-pattern="email.EMAIL_FORMAT"
                   placeholder="{{email.EMAIL_FORMAT_HELP}}"
                   ng-model="mail.to"/>
            <small class="text-muted" ng-show="emailModal.To.$error.pattern">wrong</small>
        </div>
    </div>
</ng-form>

我找到了很好的在线正则表达式测试工具。用测试覆盖了我的正则表达式:

https://regex101.com/r/Dg2iAZ/6/tests

于 2018-10-29T16:13:21.020 回答
0

angularjs 控制器方式,只是在邮件正文中查找一封或多封电子邮件的示例。

sp = $scope.messagebody; // email message body

if (sp != null && sp.match(/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+/)) {   
console.log('Error. You are not allowed to have an email in the message body');
}
于 2016-09-20T13:15:39.057 回答
0

我已经尝试过以下正则表达式,它工作正常。

电子邮件验证: \w+([-+.']\w+) @\w+([-.]\w+) .\w+([-.]\w+)*

于 2018-10-08T12:11:04.437 回答
-1

使用下面的正则表达式

^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+)+((\.)[a-z]{2,})+$

它允许

test@test.com
test@test.co.in
test@test.gov.us
test@test.net
test@test.software
于 2019-02-19T05:25:53.390 回答