How to validate email in C#?

How to validate email in C#?

How to validate email in C#?

As a programmer, it is important to validate all the emails before adding to a database. This helps prevent invalid email addresses from being entered into your system and helps to reduce the risk of your emails being flagged as spam or bounced back.

Each email should have a valid format and additionally, they are from valid domains. Here, we will cover the following validations:

  • Validate the format of the email.
  • Validate the domain name of the email.

A. Validate Email Format

In C#, we can validate the format of the email using the following ways:

  • Manually (without using regex or built-in class)
  • Using regex (Recommended)
  • Using built-in Class

1 - Validate Email Format Manually

We can validate the email by splitting the email address into local and domain components and checking each component separately.

Example: Validate Email Format Copy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ValidateEmailFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            string email = "[email protected]";
            bool isValid = ValidateEmail(email);

            Console.WriteLine($"Is {email} a valid email?: {isValid}");
            Console.ReadLine();
        }
        static bool ValidateEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return false;
            }

            string[] parts = email.Split('@');
            if (parts.Length != 2)
            {
                return false; // email must have exactly one @ symbol
            }

            string localPart = parts[0];
            string domainPart = parts[1];
            if (string.IsNullOrWhiteSpace(localPart) || string.IsNullOrWhiteSpace(domainPart))
            {
                return false; // local and domain parts cannot be empty
            }

            // check local part for valid characters
            foreach (char c in localPart)
            {
                if (!char.IsLetterOrDigit(c) && c != '.' && c != '_' && c != '-')
                {
                    return false; // local part contains invalid character
                }
            }

            // check domain part for valid format
            if (domainPart.Length < 2 || !domainPart.Contains(".") || domainPart.Split('.').Length != 2 || domainPart.EndsWith(".") || domainPart.StartsWith("."))
            {
                return false; // domain part is not a valid format
            }

            return true;
        }
    }
}

Output:

How to validate email in C#? - XdevSpace

In the above example, we first check if the email address contains exactly one @ symbol, then splits the email into the local part and domain part.

We then check if both parts are not empty, and if the local part contains valid characters only (letters, digits, dots, underscores, and hyphens).

Finally, it checks if the domain part is a valid format by checking if it has at least two characters and does not start or end with a dot and also it should contain a dot.

2 - Validate Email Format using Regex

We can validate the email using a regular expression in C#. Regular expressions are a powerful tool for text pattern matching and manipulation.

The following validates the email using regex:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace ValidateEmailFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            string email = "[email protected]";
            bool isValid = IsValidEmail(email);

            Console.WriteLine($"Is {email} a valid email? ==> {isValid}");
            Console.ReadLine();
        }
        public static bool IsValidEmail(string email)
        {
            string emailPattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";

            if (string.IsNullOrEmpty(email))
                return false;

            Regex regex = new Regex(emailPattern);
            return regex.IsMatch(email);
        }
    }
}

Output:

Validate Email Format using Regex

In the above example, the IsValidEmail function checks whether the given email address matches the specified pattern. 

The emailPattern variable contains a regular expression to match common email addresses.

3 - Validate Email using Built-in Class

Another approach is to use the MailAddress class included in the System.Net.Mail namespace, as shown below.

Example: Validate Email using MailAddress

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;

namespace ValidateEmailFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            string email = "[email protected]";
            bool isValid = isValidEmail(email);

            Console.WriteLine($"Is {email} a valid email? ==> {isValid}");
            Console.ReadLine();
        }
        static bool isValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return false;
            }

            try
            {
                // Use MailAddress class to validate email format
                var addr = new MailAddress(email);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

Output:

Validate Email using Built-in Class

In the above example, the MailAddress class in .NET to validate the format of the email. If the MailAddress constructor throws an exception, it means the email is invalid. Otherwise, it is valid.

Note that this code only validates the format of the email address. It does not check if the email actually exists or is deliverable.

B. Validate the Domain Name of the Email

We can also validate whether the domain part of the specified email is valid or not by checking its MX record. By performing a DNS lookup on the domain name, we can ensure that the email address is associated with a valid domain. This is a little slow process so performance may impact. So, it is advisable to validate the domain only if it is required.

Example: Validate Domain

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace ValidateEmailFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            string email = "[email protected]";
            bool isValid = isValidEmailDomain(email);

            Console.WriteLine($"Is {email} a valid email? ==> {isValid}");
            Console.ReadLine();
        }
        static bool isValidEmailDomain(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return false;
            }

            string[] parts = email.Split('@');
            if (parts.Length != 2)
            {
                return false; // email must have exactly one @ symbol
            }

            string localPart = parts[0];
            string domainPart = parts[1];

            try
            {
                // check if domain name has a valid MX record
                var hostEntry = Dns.GetHostEntry(domainPart);
                return hostEntry.HostName.Length > 0;
            }
            catch
            {
                return false; // domain name is invalid or does not have a valid MX record
            }
        }
    }
}

Output:

Validate the Domain Name of the Email

In the above example, the Dns.GetHostEntry() method perform a DNS lookup on the domain name and get its host entry. If the domain has at least one MX record, it is considered valid.

Thus, we can validate emails using various ways. Choose any of them based on your requirement.

All Comments