How can I make a textbox only accept a valid email?

26,269

.NET can do it for you:

  bool IsValidEmail(string eMail)
  {
     bool Result = false;

     try
     {
        var eMailValidator = new System.Net.Mail.MailAddress(eMail);

        Result = (eMail.LastIndexOf(".") > eMail.LastIndexOf("@"));
     }
     catch
     {
        Result = false;
     };

     return Result;
  }
Share:
26,269
Nickz2
Author by

Nickz2

Job: Software Developer Languages: C#, SQL, Javascript, JQuery, HTML, CSS, ASP.NET, WebForms, Windows Forms etc. Phone: Huawei P10 - Android Football Team: Swindon Town FC Games: Fifa, Call of Duty, Rocket League, Terraria, Fortnite etc.

Updated on September 10, 2021

Comments

  • Nickz2
    Nickz2 over 2 years

    I would like my textbox to check if the email that is entered into the textbox is valid.

    So far I have got:

    if (!this.txtEmail.Text.Contains('@') || !this.txtEmail.Text.Contains('.')) 
    { 
        MessageBox.Show("Please Enter A Valid Email", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    }
    

    But this only tests if it has a '@' and a '.' in it.

    Is there a way to make it check to see if it has .com etc. and only one '@'?