How to validate an email address in C#?

Email validation is a crucial aspect of data validation in C# applications. There are several effective approaches to validate email addresses, each with its own advantages and use cases.

Using MailAddress Class

The MailAddress class from the System.Net.Mail namespace provides a simple way to validate email addresses by attempting to parse them. If the parsing succeeds, the email format is considered valid −

Example

using System;
using System.Net.Mail;

class EmailValidator {
    public static bool IsValidEmail(string email) {
        try {
            var mail = new MailAddress(email);
            return mail.Address == email;
        }
        catch {
            return false;
        }
    }

    public static void Main() {
        string[] emails = { "test@example.com", "invalid-email", "user@domain.co.uk" };
        
        foreach (string email in emails) {
            bool isValid = IsValidEmail(email);
            Console.WriteLine($"{email} is {(isValid ? "valid" : "invalid")}");
        }
    }
}

The output of the above code is −

test@example.com is valid
invalid-email is invalid
user@domain.co.uk is valid

Using Regular Expressions

Regular expressions provide more granular control over email validation. The System.Text.RegularExpressions namespace offers the Regex class for pattern matching −

Example

using System;
using System.Text.RegularExpressions;

class RegexEmailValidator {
    private static readonly string emailPattern = 
        @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
    
    public static bool IsValidEmail(string email) {
        if (string.IsNullOrWhiteSpace(email)) return false;
        
        return Regex.IsMatch(email, emailPattern, RegexOptions.IgnoreCase);
    }

    public static void Main() {
        string[] emails = { "user@domain.com", "test.email+tag@example.org", "invalid.email" };
        
        foreach (string email in emails) {
            bool isValid = IsValidEmail(email);
            Console.WriteLine($"{email} is {(isValid ? "valid" : "invalid")}");
        }
    }
}

The output of the above code is −

user@domain.com is valid
test.email+tag@example.org is valid
invalid.email is invalid

Comprehensive Email Validation

For production applications, combining both approaches provides robust validation that checks both format and structural validity −

Example

using System;
using System.Net.Mail;
using System.Text.RegularExpressions;

class ComprehensiveValidator {
    private static readonly string emailPattern = 
        @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
    
    public static bool IsValidEmail(string email) {
        if (string.IsNullOrWhiteSpace(email)) return false;
        
        // First check with regex for basic format
        if (!Regex.IsMatch(email, emailPattern, RegexOptions.IgnoreCase)) {
            return false;
        }
        
        // Then verify with MailAddress for structural validity
        try {
            var mail = new MailAddress(email);
            return mail.Address == email;
        }
        catch {
            return false;
        }
    }

    public static void Main() {
        string[] testEmails = { 
            "valid@example.com", 
            "user.name+tag@domain.co.uk", 
            "invalid@", 
            "@invalid.com", 
            "spaces @domain.com" 
        };
        
        foreach (string email in testEmails) {
            bool isValid = IsValidEmail(email);
            Console.WriteLine($"'{email}' is {(isValid ? "valid" : "invalid")}");
        }
    }
}

The output of the above code is −

'valid@example.com' is valid
'user.name+tag@domain.co.uk' is valid
'invalid@' is invalid
'@invalid.com' is invalid
'spaces @domain.com' is invalid

Comparison of Validation Methods

Method Advantages Disadvantages
MailAddress Class Simple to use, built-in .NET validation May accept some technically invalid formats
Regular Expressions Precise control over validation rules Complex patterns can be hard to maintain
Combined Approach Most comprehensive validation Slightly more processing overhead

Common Use Cases

  • User Registration: Use comprehensive validation to ensure quality user data.

  • Contact Forms: Basic regex validation is often sufficient for simple forms.

  • Bulk Email Processing: MailAddress validation for quick format checking.

Conclusion

Email validation in C# can be accomplished using the MailAddress class for simple validation or regular expressions for more precise control. For production applications, combining both methods provides the most robust validation by checking both format and structural validity of email addresses.

Updated on: 2026-03-17T07:04:36+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements