0

I am using RegularExpressionValidator to validate multiple email addresses seprated by a comma ","

My below expression works fine for this requirment:

"((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*"

Requirment is this expression should be able to handle space after comma in email addresses.

For example my current expression work file for email1@domain.com,email2@domain.com but what it do not do is email1@domain.com, email2@domain.com

I understand there can be many solutions but in my snario best is to enhance this expression.

Please guide me

user576510
  • 5,777
  • 20
  • 81
  • 144
  • I can't answer your question, but I do want to point out that your regex [isn't optimal](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses) –  Nov 22 '11 at 06:38

3 Answers3

5

You could use your existing regular expression and instead split the string by each comma and trim trailing/leading whitespace:

var emails = input.Split(',');
foreach (var email in emails.Select(ee => ee.Trim()))
{
    if (!emailValidator.IsMatch(email))
    {
        // announce a bad email
    }
}
user7116
  • 63,008
  • 17
  • 141
  • 172
1

Here is my suggestion:

((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*

That will accept blanks between the e-mail addresses

Fischermaen
  • 12,238
  • 2
  • 39
  • 56
  • Thanks @Fischermaen, your suggestion worked. But can you please also guide why "((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,\s])*)*" not work, I read \s indicate a space ? Please guide. – user576510 Nov 22 '11 at 06:37
  • 2
    Inside the square brackets every character is interpreted as a character and `\s` will match a `\` and a `s` and not a whitespace as you intended. – Fischermaen Nov 22 '11 at 06:40
1

Besides what Fischermaen said, another options could be to split emails into separate emails, and then validate each email separately.

   var emails = emailString.split(',');
   for(var i = 0; i < emails.length; i++){
      var email = emails[i].trim().replace(',', '');
      // Now you can validate a single, comma-less, space-less email;
   }
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188