How to Validate Email Using C# - Simple and Effective
To validate an email in C#, use the
System.Net.Mail.MailAddress class to check format validity or use a regular expression with Regex.IsMatch for pattern matching. Both methods help ensure the email string is correctly formatted before use.Syntax
There are two common ways to validate an email in C#:
- Using
MailAddressclass: Create a newMailAddressobject with the email string. If it throws an exception, the email is invalid. - Using
Regex.IsMatchmethod: Use a regular expression pattern to check if the email matches the expected format.
csharp
using System.Net.Mail; using System.Text.RegularExpressions; // Using MailAddress try { var email = new MailAddress("example@domain.com"); // Valid email if no exception } catch { // Invalid email } // Using Regex string pattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$"; bool isValid = Regex.IsMatch("example@domain.com", pattern);
Example
This example shows how to validate an email using both MailAddress and Regex. It prints whether the email is valid or not.
csharp
using System; using System.Net.Mail; using System.Text.RegularExpressions; class Program { static bool ValidateEmailWithMailAddress(string email) { try { var addr = new MailAddress(email); return true; } catch { return false; } } static bool ValidateEmailWithRegex(string email) { string pattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$"; return Regex.IsMatch(email, pattern); } static void Main() { string[] emails = { "user@example.com", "invalid-email", "test@domain.co.uk" }; foreach (var email in emails) { Console.WriteLine($"Validating: {email}"); Console.WriteLine($"MailAddress valid? {ValidateEmailWithMailAddress(email)}"); Console.WriteLine($"Regex valid? {ValidateEmailWithRegex(email)}"); Console.WriteLine(); } } }
Output
Validating: user@example.com
MailAddress valid? True
Regex valid? True
Validating: invalid-email
MailAddress valid? False
Regex valid? False
Validating: test@domain.co.uk
MailAddress valid? True
Regex valid? True
Common Pitfalls
Common mistakes when validating emails in C# include:
- Using overly simple regular expressions that allow invalid emails or reject valid ones.
- Relying only on
Regexwithout considering exceptions thatMailAddresshandles. - Not trimming whitespace before validation, causing false negatives.
- Assuming validation guarantees deliverability; it only checks format.
csharp
using System; using System.Net.Mail; using System.Text.RegularExpressions; class PitfallExample { static void Main() { string email = " user@example.com "; // Has spaces // Wrong: No trimming bool regexValid = Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"); Console.WriteLine($"Regex valid without trim: {regexValid}"); // False // Right: Trim before validating email = email.Trim(); bool mailAddressValid = false; try { var addr = new MailAddress(email); mailAddressValid = true; } catch { } Console.WriteLine($"MailAddress valid after trim: {mailAddressValid}"); // True } }
Output
Regex valid without trim: False
MailAddress valid after trim: True
Quick Reference
Summary tips for email validation in C#:
- Use
MailAddressfor simple and reliable format checking. - Use
Regexfor custom pattern needs but choose patterns carefully. - Always trim input strings before validation.
- Remember validation checks format, not if the email actually exists.
Key Takeaways
Use System.Net.Mail.MailAddress to validate email format safely with exception handling.
Regular expressions can validate email patterns but require careful pattern choice.
Always trim whitespace from email strings before validating.
Email validation only checks format, not actual email existence or deliverability.
Combine methods if needed for stronger validation but keep it simple for most cases.