How To Validate Email ID in C#?

Validating email addresses is a common task in C# applications, especially when dealing with user input or processing email-related functionality. It is very important to validate an Email ID before storing it in our database.


All Email IDs must follow a specific format and must belong to some domain. Here in this article, we are going to cover three different methods that we can use for email validation. 


Email Format Validation.

In C# we can validate an Email ID using the below methods:

  • Using Regular Expression.
  • Using Built-in Library Function.
  • Using Custom Validation.

Let's understand each of these methods in detail with C-sharp Code.


Method 1: Using Regular Expression.

Using a regular expression is a robust way to validate email addresses. It allows you to define complex patterns that match valid email formats.


C# Example Code:

// C#-sharp code to validate email id using Regular Expression
using System;
using System.Text.RegularExpressions;

class EmailValidator
{
    public static bool IsValidEmail(string email)
    {
        // Define a regular expression pattern for valid email addresses
        string pattern = @"^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$";

        // Use Regex.IsMatch to check if the email matches the pattern
        return Regex.IsMatch(email, pattern);
    }

    static void Main()
    {
        string email = "example@email.com";
        bool isValid = IsValidEmail(email);
        
        Console.WriteLine($"Is {email} a valid email address? {isValid}");
    }
}
Output:
Is example@email.com a valid email address? True

Explanation of Above C# Code:
  • We define a regular expression pattern that describes valid email addresses.
  • The pattern ^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$ checks for common email format rules.
  • Regex.IsMatch(email, pattern) tests if the email string matches the pattern.
  • The IsValidEmail method returns true if the email is valid.

Method 2: Using Regular Expression.

C# also provides a built-in library, System.Net.Mail, for email-related tasks, including email address validation.

C# Example Code:

// C#-sharp code to validate email id using Built-in Library
using System;
using System.Net.Mail;

class EmailValidator
{
    public static bool IsValidEmail(string email)
    {
        try
        {
            var mailAddress = new MailAddress(email);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }

    static void Main()
    {
        string email = "algolesson@email.com";
        bool isValid = IsValidEmail(email);
        
        Console.WriteLine($"Is {email} a valid email address? {isValid}");
    }
}
Output:
Is algolesson@email.com a valid email address? True

Explanation of Above C# Code:
  • We create a MailAddress object with the given email string.
  • If the email string is not a valid email address, a FormatException is thrown.
  • We catch the exception and return false for invalid emails.

Method 3: Using Custom Validation.

For basic validation without using regular expressions or libraries, you can implement a simple custom validation method.

C# Example Code:

// C#-sharp code to validate email id using Custom Validation
using System;

class EmailValidator
{
    public static bool IsValidEmail(string email)
    {
        if (string.IsNullOrWhiteSpace(email))
            return false;

        if (!email.Contains("@") || !email.Contains("."))
            return false;

        // Additional checks can be added based on your requirements
        
        return true;
    }

    static void Main()
    {
        string email = "algolesson@email.com";
        bool isValid = IsValidEmail(email);
        
        Console.WriteLine($"Is {email} a valid email address? {isValid}");
    }
}
Output:
Is algolesson@email.com a valid email address? True

Explanation of Above C# Code:
  • We perform basic checks like ensuring the email is not null or empty and contains both "@" and ".".
  • You can add additional checks based on your specific requirements.

So these are a few methods that you can use to validate your email id in C# choose any one of them that is best for you according to your use and requirement.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS