如何使用Regex验证多封电子邮件

How to validate multiple emails using Regex?

本文关键字:电子邮件 验证 何使用 Regex      更新时间:2023-09-26

在对Stackoverflow进行了快速研究后,我无法找到任何使用regex进行多封电子邮件验证的解决方案(split JS函数不适用,但由于某种原因,应用程序的后端会等待一个由;分隔的电子邮件字符串)。

以下是要求:

  1. 应使用以下规则验证电子邮件:[A-Za-z0-9'._%-]+@[A-Za-z0-9'.-]+'.[A-Za-z]{2,4}
  2. Regex应接受;符号作为分隔符
  3. 电子邮件可以写在多行上,以;结尾
  4. Regex可以接受行的末尾为;

我想出了这个解决方案:

^[A-Za-z0-9''._%-]+@[A-Za-z 0-9''.-]+''.[A-Za-z]{2,4}*

但它不适用于点#3-4

因此,以下是可以的情况:

1.john@smith.com;john@smith.com2.john@smith.com;john@smith.com;3.john@smith.com;john@smith.com;jjoh@smith.com;

以下是明显不正常的情况:

1.john@smith.comjackob@smith.com2.jackob@smith.com,3.daniels@mail.comsmth@mail.com

将感谢您的各种帮助

我就是这样做的(ASP.Net应用程序,没有jQuery)。电子邮件地址列表在多行文本框中输入:

function ValidateRecipientEmailList(source, args)
{
  var rlTextBox     = $get('<%= RecipientList.ClientID %>');
  var recipientlist = rlTextBox.value;
  var valid         = 0;
  var invalid       = 0;
  // Break the recipient list up into lines. For consistency with CLR regular i/o, we'll accept any sequence of CR and LF characters as an end-of-line marker.
  // Then we iterate over the resulting array of lines
  var lines = recipientlist.split( /['r'n]+/ ) ;
  for ( i = 0 ; i < lines.length ; ++i )
  {
    var line = lines[i] ; // pull the line from the array
    // Split each line on a sequence of 1 or more whitespace, colon, semicolon or comma characters.
    // Then, we iterate over the resulting array of email addresses
    var recipients = line.split( /[:,; 't'v'f'r'n]+/ ) ;
    for ( j = 0 ; j < recipients.length ; ++j )
    {
      var recipient = recipients[j] ;
      if ( recipient != "" )
      {
        if ( recipient.match( /^([A-Za-z0-9_-]+'.)*[A-Za-z0-9_-]+'@([A-Za-z0-9_-]+'.)+[A-Za-z]{2,4}$/ ) )
        {
          ++valid ;
        }
        else
        {
          ++invalid ;
        }
      }
    }
  }
  args.IsValid = ( valid > 0 && invalid == 0 ? true : false ) ;
  return ;
}
var email = "[A-Za-z0-9'._%-]+@[A-Za-z0-9'.-]+'.[A-Za-z]{2,4}";
var re = new RegExp('^'+email+'(;''n*'+email+')*;?$');
[ "john@smith.com;john@smith.com",
  "john@smith.com;john@smith.com;",
  "john@smith.com;'njohn@smith.com;'njjoh@smith.com",
  "john@smith.com jackob@smith.com",
  "jackob@smith.com,",
  "daniels@mail.com'nsmth@mail.com" ].map(function(str){
    return re.test(str);
}); // [true, true, true, false, false, false]

没有理由不使用拆分-就像后端显然会做的那样。

return str.split(/;'s*/).every(function(email) {
    return /.../.test(email);
}

对于好的或不太好的电子邮件正则表达式,请查看验证JavaScript中的电子邮件地址?。