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

时间:2012-03-20 02:20:40

标签: javascript regex email-validation

经过对Stackoverflow的快速研究后,我无法找到使用正则表达式进行多重电子邮件验证的任何解决方案(拆分JS功能不适用,但某些原因导致应用程序的后端等待带有电子邮件的字符串由;分隔。

以下是要求:

  1. 应使用以下规则验证电子邮件:[A-Za-z0-9\._%-]+@[A-Za-z0-9\.-]+\.[A-Za-z]{2,4}
  2. 正则表达式应接受;符号作为分隔符
  3. 电子邮件可以写在多行上,以;
  4. 结束
  5. 正则表达式可以接受该行的结尾为;
  6. 我想出了这个解决方案:

    ^[A-Za-z0-9\._%-]+@[A-Za-z0-9\.-]+\.[A-Za-z]{2,4}(?:[;][A-Za-z0-9\._%-]+@[A-Za-z0-9\.-]+\.[A-Za-z]{2,4}?)*
    

    但它不适用于第3-4点

    所以这里的情况还可以:

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

    以下是定义不正确的情况:

      1. john@smith.com jackob@smith.com
      2. jackob@smith.com,
      3. daniels@mail.com
         smth@mail.com
    

    所有类型的帮助将不胜感激

3 个答案:

答案 0 :(得分:2)

这就是我的做法(ASP.Net app,no 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 ;
}

答案 1 :(得分:1)

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]

答案 2 :(得分:1)

没有理由不使用拆分 - 后端显然也会这样做。

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

对于好的或不那么好的电子邮件,正则表达式会查看Validate email address in JavaScript?