如何使用ng-pattern验证angularJs中的电子邮件ID

时间:2014-06-30 12:56:37

标签: regex angularjs email angularjs-directive ng-pattern

尝试使用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>

12 个答案:

答案 0 :(得分:60)

如果要验证电子邮件,请使用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

UPD:

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

  

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

答案 1 :(得分:50)

如何处理修改内置验证器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>  

答案 2 :(得分: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>

答案 3 :(得分:6)

这是使用Regex Expression的jQuery Email Validation。如果您了解AngularJS,也可以对AngularJS使用相同的概念。

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

Source

答案 4 :(得分:3)

您可以使用ng-messages

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

包含模块

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

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

答案 5 :(得分: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>

答案 6 :(得分:2)

现在,Angular 4内置了电子邮件验证程序 https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://github.com/angular/angular/pull/13709

只需将电子邮件添加到代码中即可。例如

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

答案 7 :(得分: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');
}

答案 8 :(得分:0)

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

  1. https://regex101.com/
  2. https://www.regextester.com/
  3. https://regexr.com/
  4. 然后我将其修改为有效。

    /([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+
    

答案 9 :(得分:0)

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

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

答案 10 :(得分: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

答案 11 :(得分:0)

在正则表达式下使用

^[_\.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