Validate multiple emails on editor

Dani_S 3,786 Reputation points
2024-03-24T14:41:48.04+00:00

Hi,

I have editor and user insert multi emails sepertated by semicolon .

I need to validate them.

  1. How I can valid them efficently. If you could give me how you validate email please look on IsValidEmail

method?

/// <summary>
 /// Check if email reciepents is valid
 /// </summary>
 /// <param name="reciepents">The reciepents seperated by coma(;)</param>
 /// <returns>Return true if reciepents string is valid, otherwise return false</returns>
 public static bool IsValidReciepents(string reciepents)
 {
     try
     {
         if (string.IsNullOrEmpty(reciepents))
         {
             return false;
         }
         string[] tmpEmails = reciepents.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
         foreach (var address in tmpEmails.Select(s => s.Trim()).Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray())
         {
             var isEmailValid = IsValidEmail(address);
             if (!isEmailValid)
             {
                 return false;
             }
         }
         return true;
     }
     catch (Exception ex)
     {
         _logger.Error("IsValidReciepents", ex);
         return false;
     }
 }
/// <summary>
  /// Check if input string is valid
  /// </summary>
  /// <param name="inputString">The input string to check</param>
  /// <returns>Return true if input string is valid, otherwise return false</returns>
  public static bool IsValidEmail(string inputString)
  {
      try
      {
          MailAddress mailAddress = new MailAddress(inputString);
          return true;
      }
      catch(Exception ex)
      {
          return false;
      }
  }

Thanks in advance,

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,504 questions
{count} votes

Accepted answer
  1. Andre Baltieri 160 Reputation points
    2024-03-24T23:59:42.97+00:00

    It depends on how many emails you need to validate. If they're just a few, you can use MailAddres or even use a Regular Expression for it.

    var pattern = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"; 
    if(Regex.IsMatch(val ?? "", pattern))
        // Do what you want
    

    Another thing to think about is throw an exception... Do you really need it? All exceptions have a cost, so can be more efficient just do nothing.

    Here's a complete example

    // Let's supose you already have a property Email being filled with addresses separated by coma
    public void OnSubmit()
    {
        const string pattern = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"; 
        var validEmails = new List<string>();
        foreach(var item in Email.Split(","))
        {
            if(Regex.IsMatch(item ?? "", pattern))
                validEmails.Add(item);
        }
    
        // Now you have a list with only valid emails
        ...
    }
    
    
    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.