email validation in a c# winforms application

10,985

Solution 1

You can use Regular Expressions to validate Email addresses:

RegEx reg=new RegEx(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$", RegexOptions.IgnoreCase); ///Object initialization for Regex 
if(reg.IsMatch("email string"))
    //valid email

Solution 2

The best way would be to forward this validation task to .NET itself:

public bool IsValidEmailAddress (string email)
{
    try
    {
        MailAddress ma = new MailAddress (email);

        return true;
    }
   catch
   {
        return false;
   }
}

Granted, it will fire false positives on some technically valid email addresses (with non-latin characters, for example), but since it won't be able to send to those addresses anyway, you can as well filter them out from the start.

Solution 3

This page has a good regular expression matching email addresses.

Remember this is only a formal check. To check whether an email address really exists, you have to send an actual email to the address and check the mail server's response.

And even if this succeeds, the SMTP server might be configured to ignore invalid recipient addresses.

Solution 4

If you want to validate the address format, you should probably use a regular expression. There are thousands of examples out there, so I'll let you find and pick the best one.

If you want to validate that an address exists, this article gives some pointers about how to do so, without giving any specific code examples.

Share:
10,985
Nagu
Author by

Nagu

Updated on June 11, 2022

Comments

  • Nagu
    Nagu almost 2 years

    Hi how can i validate email in c# winforms ?

  • Mark Maslar
    Mark Maslar almost 15 years
    IsValidEmailAddress returns true even if the TLD is missing. e.g. myname@mycompany succeeds.
  • User
    User almost 15 years
    @Mark Maslar: Yes, I know. These are valid email addresses, though you don't usually get one of those.
  • Junior Mayhé
    Junior Mayhé over 14 years
    indeed a good link explaining in PHP how to establish connection in order to very the remote server, although it has nothing to do with C#
  • Dinah
    Dinah about 14 years
    This will only work if it is case-insensitive. Include RegexOptions.IgnoreCase
  • Treycos
    Treycos over 5 years
    Try adding a written explanation alongside your code