4

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 '@'?

Nickz2
  • 93
  • 2
  • 4
  • 14
  • 1
    Validating email addresses is difficult. The easiest way is to do, what you already did: look for `@` and `.`. If those are present, send an email to that address and let the user confirm its authenticity. – germi Apr 23 '15 at 10:35
  • Check this [regex](https://regex101.com/r/jZ3jT5/1) – Izzy Apr 23 '15 at 10:41
  • Most of the different UI (and web) frameworks in the C# space have validators, and usually also one specifically for validating email addresses. – Mark Rotteveel Apr 23 '15 at 14:09

3 Answers3

7

.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;
  }
Michael
  • 67
  • 2
  • 8
Jack
  • 258
  • 2
  • 15
0

Check the MailAddress class

    var email = new MailAddress("abc123@example.com");
its4zahoor
  • 1,489
  • 1
  • 15
  • 19
Matheno
  • 3,977
  • 6
  • 33
  • 51
0

If you're developing a web app, modern browsers support HTML5, so you can use <input id="txtEmail" type="email" runat="server" /> instead of a TextBox and it will validate the input is an email in the browser (but you should also validate it in your code). Use txtEmail.Value to get the text string.

IglooGreg
  • 147
  • 5