๐ Introduction
Validating email addresses is a common need in many C# applications โ from sign-up forms and contact pages to backend input validation. Using regular expressions (regex) is a popular method for verifying whether a string appears to be an email address. In this article, youโll learn simple, practical, and SEO-friendly ways to validate emails in C# using regex, plus safer alternatives and best practices.
What is an Email Validation Regex?
A regular expression is a pattern that describes text. An email regex checks whether an input string follows standard email rules, like:
Contains exactly one @
symbol
Has a local-part (before the @
) and a domain (after the @
)
The domain contains at least one.
And valid characters
No illegal characters or spaces
Important: A regex can only verify the format of an email โ it cannot check if the email actually exists or receives mail. For that, you need to send a verification email or use an email validation service.
Practical and straightforward Regex Patterns
Below are a few commonly used regular expression (regex) patterns, ranging from simple/lenient to stricter. Select one option based on your project's needs.
๐น 1. Very simple (useful for quick checks)
This pattern checks for [email protected]
with no spaces.
string pattern = @"^\S+@\S+\.\S+$"; // simple, short
Pros: Fast, easy, fewer false negatives.
Cons: Accepts invalid emails like [email protected]
or name@localhost
.
๐น 2. Common practical regex (balanced)
A balanced approach suitable for most web apps. It allows letters, numbers, dots, hyphens, and underscores in the local part and domain.
string pattern = @"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$";
Pros: Good balance between strictness and usability.
Covers most real-world email formats (e.g., [email protected]
).
๐น 3. Strict RFC-like regex (very complex)
The official email formats are defined by RFC 5322 and related specs. A fully RFC-compliant regex is huge and often impractical. Still, here is a commonly quoted strict regex (beware: it's long and slower):
string pattern = @"^(?:[a-zA-Z0-9_'^&/+-])+(?:\.(?:[a-zA-Z0-9_'^&/+-])+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$";
Pros: More restrictive and closer to RFC rules.
Cons: Hard to read, slower, may still not cover every valid international (IDN) email.
How to Validate Email in C# Using Regex.IsMatch()
Hereโs a simple C# function that uses the balanced pattern above.
using System;
using System.Text.RegularExpressions;
public static bool IsValidEmail(string email)
{
if (string.IsNullOrWhiteSpace(email))
return false;
// Balanced regex pattern
string pattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
return Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase);
}
// Usage
Console.WriteLine(IsValidEmail("[email protected]")); // True
Console.WriteLine(IsValidEmail("invalid@@example")); // False
Notes:
Use RegexOptions.IgnoreCase
to make domain checks case-insensitive.
IsMatch
returns immediately when the pattern fails, so simple patterns are faster.
Using MailAddress
as a Safer Alternative
C# has a built-in type System.Net.Mail.MailAddress
that parses addresses and throws an exception for many invalid formats. Itโs a good additional check but not a full verification.
using System;
using System.Net.Mail;
public static bool IsValidEmailUsingMailAddress(string email)
{
try
{
var addr = new MailAddress(email);
return addr.Address == email; // extra check to avoid trimmed/altered input
}
catch
{
return false;
}
}
Tip: Combine Regex.IsMatch()
with MailAddress
if you want both format-checking and parsing validation.
Internationalized Emails and IDN (Unicode Domains)
Modern email systems support internationalized domain names (IDN) and Unicode in the local part. Classic ASCII-only regex patterns will reject these valid addresses.
Strategy:
Use IdnMapping
to convert Unicode domain to ASCII (Punycode) before validation.
Then validate the converted domain with your regex.
using System.Globalization;
using System.Text.RegularExpressions;
using System.Net.Mail;
public static bool IsValidEmailWithIdn(string email)
{
if (string.IsNullOrWhiteSpace(email))
return false;
try
{
// Split local and domain parts
int atIndex = email.LastIndexOf('@');
if (atIndex < 0) return false;
string local = email.Substring(0, atIndex);
string domain = email.Substring(atIndex + 1);
var idn = new IdnMapping();
domain = idn.GetAscii(domain); // convert to punycode if needed
string normalized = local + "@" + domain;
// Use balanced regex
string pattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
return Regex.IsMatch(normalized, pattern, RegexOptions.IgnoreCase);
}
catch
{
return false;
}
}
Checking If Email Actually Exists (Beyond Regex)
Regex only checks format. To verify an email truly exists, consider:
Send a verification email with a unique token โ the gold standard.
Use SMTP check: try connecting to recipient's mail server (may be unreliable or blocked).
Third-party validation APIs: services that combine MX checks, SMTP probes, and reputation checks.
Performance and Security Tips
Use a lean regex for high-traffic validation (avoid the monstrous RFC regex if performance matters).
Cache compiled regex using RegexOptions.Compiled
for repeated checks (but test startup time).
Sanitize inputs before logging to avoid leaking user data.
Limit attempts to prevent abuse on signup endpoints.
// Compiled regex example
private static readonly Regex _emailRegex = new Regex(
"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$",
RegexOptions.IgnoreCase | RegexOptions.Compiled
);
public static bool IsValidEmailCompiled(string email) => _emailRegex.IsMatch(email);
Unit Tests and Examples
Write unit tests to validate typical and edge-case emails:
Example NUnit test snippet:
[TestCase("[email protected]", true)]
[TestCase("plainaddress", false)]
[TestCase("[email protected]", true)]
public void EmailValidationTests(string email, bool expected)
{
Assert.AreEqual(expected, IsValidEmail(email));
}
Summary
Validating email addresses in C# is usually a two-step process:
Format validation: Use a pragmatic regex (^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
) for most web apps.
Parsing validation: Optionally use System.Net.Mail.MailAddress
and IdnMapping
for safer parsing and internationalized domains.
Remember that regex only checks format โ to ensure a mailbox exists, send a verification email or use a specialized API.