How to Validate an email address using Regular Expression in C# ?

Published on February 10, 2016 by abundantcode

Filed under C#

Last modified February 9, 2016

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 5296 times

You can validate an email address in C# using regular expressions which provides the developers to play around with different patterns.

Below is a code snippet that shows how you can use regular expression to validate an email address in C# .

How to Validate an email address using Regular Expression in C# ?

using System;
using System.Text.RegularExpressions;

namespace ACCode
{
    class Program
    {
        static void Main(string[] args)
        {
            var result1 = IsEmailAddressValid("test@gmail");
            var result2 = IsEmailAddressValid("test@gmail.com");
            Console.WriteLine(result1);
            Console.WriteLine(result2);
            Console.ReadLine();
        }
        // Method to validate email address using regular expression in C#
        public static bool IsEmailAddressValid(string emailAddress)
        {
            string EmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
            + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
            + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
            Regex regex = new Regex(EmailPattern, RegexOptions.IgnoreCase);
            bool isValid = regex.IsMatch(emailAddress);
            return isValid;
        }

    } 
}

Leave a Comment


x

You might be Interested in these Posts

C Program to find the G.C.D of a number using Recursive function

Problem Write a program in C to find the find the G.C.D of a number using recursion and display the ...

C Program to print a Half Pyramid using *

Problem Write a program in C to print Half pyramid using * as shown. * * * * * * * * * * ...

C Program to display Positive factors of a number

Problem Write a program in C to display all the positive factors of a number enter by the user. Ho...