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
  • 3
  • 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
  • 77
  • 1
  • 8
Jack
  • 350
  • 2
  • 15
  • If i use "test@test" this passes as a valid email address using this approach. – DDuffy Oct 13 '16 at 12:15
  • Although it is useful, it doesn't check for a correct email address format, like @DDuffy said, passing "test@test" results as a "valid" email. – Jesús Hagiwara Jul 27 '19 at 15:20
0

Check the MailAddress class

    var email = new MailAddress("abc123@example.com");
its4zahoor
  • 1,709
  • 1
  • 16
  • 23
Matheno
  • 4,112
  • 6
  • 36
  • 53
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