How to validate multiple emails using Regex?

为君一笑 提交于 2019-12-01 07:54:09
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]

This is how I'm doing it (ASP.Net app, no jQuery). The list of email addresses is entered in a multi-line text box:

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 ;
}
Bergi

There is no reason not to use split - in the same way the backend will obviously do.

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

For good or not-so-good email regular expressions have a look at Validate email address in JavaScript?.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!