How to validate an email address in C#?

CsharpServer Side ProgrammingProgramming

There are several ways to validate an email address in C#.

System.Net.Mail −The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.

System.Text.RegularExpressions − Represents an immutable regular expression.

Use the below expression

@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([azA-Z]{2,4}|[0-9]{1,3})(\]?)$"

We can use the MailAddress class of the System.Net.Mail namespace to validate an email address

Example

 Live Demo

using System;
using System.Net.Mail;
namespace DemoApplication{
   class Program{
      public static void Main(){
         try{
            string email = "hello@xyzcom";
            Console.WriteLine($"The email is {email}");
            var mail = new MailAddress(email);
            bool isValidEmail = mail.Host.Contains(".");
            if(!isValidEmail){
               Console.WriteLine($"The email is invalid");
            } else {
               Console.WriteLine($"The email is valid");
            }
            Console.ReadLine();
         }
         catch(Exception){
            Console.WriteLine($"The email is invalid");
            Console.ReadLine();
         }
      }
   }
}

Output

The output of the above code is

The email is hello@xyzcom
The email is invalid

Example using Regex

We can also use regular expression to validate an email address.

Example

using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string email = "hello@xyz.com";
         Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-
         9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
         RegexOptions.CultureInvariant | RegexOptions.Singleline);
         Console.WriteLine($"The email is {email}");
         bool isValidEmail = regex.IsMatch(email);
         if (!isValidEmail){
            Console.WriteLine($"The email is invalid");
         } else {
            Console.WriteLine($"The email is valid");
         }
         Console.ReadLine();
      }
   }
}

Output

The output of the above code is

The email is hello@xyz.com
The email is valid
raja
Published on 19-Aug-2020 11:08:05
Advertisements