Multiple emails validation with split comma in a Textbox

Donald Symmons 2,986 Reputation points
2024-11-25T16:16:54.6466667+00:00

Hi,

If I have a TetxtBox that will be used to send messages to multiple emails, how can I validate these emails that will be inputted in the textbox?

The emails are separated by comma. e.g. myfirstmail@hotmail.com, mymail@outlook.com, thirdemail@gmail.com

I want to validate the emails in the textbox and ensure that those are correct and if not, I will have an error message show that an error is in one of the emails. I only know how to validate a single input email in a textbox. I will love to know how this is done. Please how do I do that?

I am doing this because I got an error

error send (2)

Code

protected void BtnRegular_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(TextBox3.Text) & !string.IsNullOrEmpty(bodyMail.Text))
            {
                MailMessage mm = new MailMessage();
                mm.From = new MailAddress("donaldsymmons@gmail.com");
                string sentFrom = named.Text;
                string eventName = Title.Text;
                string[] ToAddress = TextBox3.Text.Split(',');
                foreach (string n in ToAddress)
                {
                    mm.To.Add(new MailAddress(n));
                }
                mm.Subject = eventName + "EVENT REGISTRATION " + sentFrom;
                mm.Body = bodyMail.Text + "<br /><br />" + URLtxtbox.Text;
                mm.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "relay-hosting.secureserver.net";
                smtp.EnableSsl = false;
                System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                NetworkCred.UserName = "donaldsymmons@gmail.com";
                NetworkCred.Password = "***********************";
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;
                smtp.Port = 25;
                smtp.Send(mm);
                dvMessage.Visible = true;
                this.dvMessage.Style.Add("background-color", "#bef1b8");
                lblMessage.Visible = true;
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text = "Your message has been sent";
            }
            else
            {
                dvMessage.Visible = true;
                this.dvMessage.Style.Add("background-color", "#ffb1b1");
                lblMessage.Visible = true;
                lblMessage.Text = "You have empty field(s)";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,973 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,536 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,097 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 55,376 Reputation points
    2024-11-25T16:30:38.47+00:00

    I assume you mean "valid" means it follows the general format of an email address and not that it is actually a valid email address (which is harder to prove). MailAddress already handles validation for basic email addresses. So you just need to create an instance of it, which you're already doing. However it throws an exception if it fails so use TryCreate if you are targeting .NET 5 or greater. If you're using NET Framework then you'll need to write your own version.

    bool TryCreateEmail ( string input, out MailAddress result )
    {
       try
       { 
          result = new MailAddress(input);
          return true;
       } catch (FormatException)  
       {
       } catch (ArgumentException)   
       { };
    
       result = null;
       return false;
    }
    

    After that it becomes a simple matter of enumerating the addresses and trying to create a mail address for each one. If any fail then you can display your message. If you want the actual emails then it becomes a little more code. If you don't care then the code is simpler.

    var emailAddresses = TextBox3.Text.Split(',').Select(x => new { EmailText = x, EmailAddress = (TryCreateEmail(x, out var result) ? result : null }).ToArray();
    
    //Get invalid email addresses
    var badAddresses = emailAddresses.Where(x => x.EmailAddress = null);
    if (badAddresses.Any())
       //Some bad ones
    

    The above code basically breaks up the address text, sends each one through a transform that returns the original text plus the email address, if any. Then you can get the bad email addresses, if any to report as errors.


3 additional answers

Sort by: Most helpful
  1. Faiz Quraishi 145 Reputation points
    2024-11-25T16:24:02.01+00:00

    You can use custom validator for it.

    Inside custom validator logic you can split the whole text by comma and apply email validator for each string ,and accordingly validate whole email addresses inside it.

    0 comments No comments

  2. Bruce (SqlWork.com) 68,001 Reputation points
    2024-11-25T19:59:27.8666667+00:00

    After the split, most likely you need to trim the leading space, I’d also trim trailing.

    0 comments No comments

  3. Lan Huang-MSFT 29,916 Reputation points Microsoft Vendor
    2024-11-28T09:26:16.52+00:00

    Hi @Donald Symmons,

    As Bruce said, based on the example you provided, your problem may be due to the presence of spaces. You can try replacing the spaces, for example:

    string[] ToAddress = TextBox3.Text.Split(',');
    foreach (string n in ToAddress)
    {            
        mm.To.Add(new MailAddress(n.Replace(" ", string.Empty)));
    }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread


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.