在单个字段中验证多个电子邮件地址 [英] Validate multiple email addresses in single field

查看:74
本文介绍了在单个字段中验证多个电子邮件地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在单个输入字段中验证一个或多个电子邮件地址?

Is there a way to validate one or multiple email addresses in a single input field?

我目前正在探索的方法是创建一个自定义指令,如果检测到逗号,该指令会将输入拆分为不同的电子邮件.这是我到目前为止的内容:

The way that I'm currently exploring is by creating a custom directive that will split the input into different emails if a comma is detected. This is what I have so far:

angular.module('myApp')
  .directive('multipleEmails', function () {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {

          var emails = viewValue.split(',');
          // loop that checks every email, returns undefined if one of them fails.
        });
      }
    };
  });

我遇到的问题是我无法手动调用角度电子邮件验证器.

The issue that I have with this is that I have been unable to call the angular email validator manually.

plunkr

事实证明我可以使用角度1.3

推荐答案

http://plnkr. co/edit/YrtXOphxkczi6cwFjvUp?p = preview

.directive('multipleEmails', function () {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {

        var emails = viewValue.split(',');
        // loop that checks every email, returns undefined if one of them fails.
        var re = /\S+@\S+\.\S+/;

        // angular.foreach(emails, function() {
          var validityArr = emails.map(function(str){
              return re.test(str.trim());
          }); // sample return is [true, true, true, false, false, false]
          console.log(emails, validityArr); 
          var atLeastOneInvalid = false;
          angular.forEach(validityArr, function(value) {
            if(value === false)
              atLeastOneInvalid = true; 
          }); 
          if(!atLeastOneInvalid) { 
            // ^ all I need is to call the angular email checker here, I think.
            ctrl.$setValidity('multipleEmails', true);
            return viewValue;
          } else {
            ctrl.$setValidity('multipleEmails', false);
            return undefined;
          }
        // })
      });
    }
  };
});

这篇关于在单个字段中验证多个电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆