email validation in a c# winforms application
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.
Nagu
Updated on June 11, 2022Comments
-
Nagu almost 2 years
Hi how can i validate email in c# winforms ?
-
Mark Maslar almost 15 yearsIsValidEmailAddress returns true even if the TLD is missing. e.g. myname@mycompany succeeds.
-
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é over 14 yearsindeed 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 about 14 yearsThis will only work if it is case-insensitive. Include
RegexOptions.IgnoreCase
-
Treycos over 5 yearsTry adding a written explanation alongside your code