C# validate email address
Here are a few ways to validate an email address in C#:
Method 1: Using a Regular Expression
using System.Text.RegularExpressions;
public bool IsValidEmail(string email)
{
var emailRegex = new Regex(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$");
return emailRegex.IsMatch(email);
}
This regular expression matches most common email address formats, but may not catch all invalid email addresses.
Method 2: Using the System.Net.Mail.MailAddress
class
using System.Net.Mail;
public bool IsValidEmail(string email)
{
try
{
var addr = new MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
This method creates a MailAddress
object from the input email address and checks if the address matches the input. If an exception is thrown, it returns false
.
Method 3: Using a third-party library
using EmailValidator;
public bool IsValidEmail(string email)
{
var validator = new EmailValidator.EmailValidator();
return validator.IsValid(email);
}
This method uses a third-party library, such as EmailValidator, to validate the email address.
Method 4: Using a custom validation method
public bool IsValidEmail(string email)
{
if (string.IsNullOrEmpty(email))
return false;
var parts = email.Split('@');
if (parts.Length!= 2)
return false;
var localPart = parts[0];
var domain = parts[1];
if (!localPart.Contains('.') &&!localPart.Contains('_') &&!localPart.Contains('-'))
return false;
if (!domain.Contains('.'))
return false;
return true;
}
This method checks if the email address has the correct format (local part, @ symbol, and domain) and contains valid characters.
You can choose the method that best fits your needs, or combine multiple methods to create a more robust email validation system.