Regex Email validation

C#RegexValidation

C# Problem Overview


I use this

@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"

regexp to validate the email

([\w\.\-]+) - this is for the first-level domain (many letters and numbers, also point and hyphen)

([\w\-]+) - this is for second-level domain

((\.(\w){2,3})+) - and this is for other level domains(from 3 to infinity) which includes a point and 2 or 3 literals

what's wrong with this regex?

EDIT:it doesn't match the "[email protected]" email

C# Solutions


Solution 1 - C#

TLD's like .museum aren't matched this way, and there are a few other long TLD's. Also, you can validate email addresses using the MailAddress class as Microsoft explains here in a note:

> Instead of using a regular expression to validate an email address, > you can use the System.Net.Mail.MailAddress class. To determine > whether an email address is valid, pass the email address to the > MailAddress.MailAddress(String) class constructor.

public bool IsValid(string emailaddress)
{
	try
	{
		MailAddress m = new MailAddress(emailaddress);

		return true;
	}
	catch (FormatException)
	{
		return false;
	}
}

This saves you a lot af headaches because you don't have to write (or try to understand someone else's) regex.

EDIT: For those who are allergic to try/catch: In .NET 5 you can use MailAddress.TryCreate. See also https://stackoverflow.com/a/68198658, including an example how to fix .., spaces, missing .TLD, etc.

Solution 2 - C#

I think @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" should work.
You need to write it like

string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
    Response.Write(email + " is correct");
else
    Response.Write(email + " is incorrect");

Be warned that this will fail if:

  1. There is a subdomain after the @ symbol.

  2. You use a TLD with a length greater than 3, such as .info

Solution 3 - C#

I have an expression for checking email addresses that I use.

Since none of the above were as short or as accurate as mine, I thought I would post it here.

@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
+ "@"
+ @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$";

For more info go read about it here: C# – Email Regular Expression

Also, this checks for RFC validity based on email syntax, not for whether the email really exists. The only way to test that an email really exists is to send and email and have the user verify they received the email by clicking a link or entering a token.

Then there are throw-away domains, such as Mailinator.com, and such. This doesn't do anything to verify whether an email is from a throwaway domain or not.

Solution 4 - C#

I found nice document on MSDN for it.

How to: Verify that Strings Are in Valid Email Format http://msdn.microsoft.com/en-us/library/01escwtf.aspx (check out that this code also supports the use of non-ASCII characters for Internet domain names.)

There are 2 implementation, for .Net 2.0/3.0 and for .Net 3.5 and higher.
the 2.0/3.0 version is:

bool IsValidEmail(string strIn)
{
    // Return true if strIn is in valid e-mail format.
    return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 
}

My tests over this method give:

Invalid: @majjf.com
Invalid: A@b@[email protected]
Invalid: Abc.example.com
Valid: [email protected]
Valid: [email protected]
Invalid: js*@proseware.com
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: ma@jjf..com
Invalid: ma@jjf.c
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: ma_@jjf.com
Invalid: -------
Valid: 12@hostname.com
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Invalid: [email protected]
Valid: j_9@[129.126.118.1]
Valid: [email protected]
Invalid: js#[email protected]
Invalid: [email protected]
Invalid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: [email protected]
Valid: ma@hostname.com
Invalid: ma@hostname.comcom
Invalid: [email protected]
Valid: [email protected]
Valid: ma[email protected]
Valid: ma[email protected]
Valid: ma[email protected]
Valid: ma[email protected]
Valid: [email protected]
Valid: ma@1hostname.com

Solution 5 - C#

The following code is based on Microsoft's Data annotations implementation on github and I think it's the most complete validation for emails:

public static Regex EmailValidation()
{
	const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
	const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

	// Set explicit regex match timeout, sufficient enough for email parsing
	// Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
	TimeSpan matchTimeout = TimeSpan.FromSeconds(2);

	try
	{
		if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null)
		{
			return new Regex(pattern, options, matchTimeout);
		}
	}
	catch
	{
		// Fallback on error
	}

	// Legacy fallback (without explicit match timeout)
	return new Regex(pattern, options);
}

Solution 6 - C#

This does not meet all of the requirements of RFCs 5321 and 5322, but it works with the following definitions.

@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";

Below is the code

const String pattern =
   @"^([0-9a-zA-Z]" + //Start with a digit or alphabetical
   @"([\+\-_\.][0-9a-zA-Z]+)*" + // No continuous or ending +-_. chars in email
   @")+" +
   @"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";

var validEmails = new[] {
        "ma@hostname.com",
        "ma@hostname.comcom",
        "MA@hostname.coMCom",
        "m.a@hostname.co",
        "m_a1a@hostname.com",
        "ma-a@hostname.com",
        "ma-a@hostname.com.edu",
        "ma-a.aa@hostname.com.edu",
        "ma.h.saraf.onemore@hostname.com.edu",
        "ma12@hostname.com",
        "12@hostname.com",
};
var invalidEmails = new[] {
        "Abc.example.com",     // No `@`
	    "A@b@c@example.com",   // multiple `@`
	    "ma...ma@jjf.co",      // continuous multiple dots in name
	    "ma@jjf.c",            // only 1 char in extension
	    "ma@jjf..com",         // continuous multiple dots in domain
        "ma@@jjf.com",         // continuous multiple `@`
        "@majjf.com",          // nothing before `@`
        "ma.@jjf.com",         // nothing after `.`
        "ma_@jjf.com",         // nothing after `_`
        "ma_@jjf",             // no domain extension 
        "ma_@jjf.",            // nothing after `_` and .
        "ma@jjf.",             // nothing after `.`
	};

foreach (var str in validEmails)
{
	Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}
foreach (var str in invalidEmails)
{
	Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}

Solution 7 - C#

Best email validation regex

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

And it's usage :-

bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

Solution 8 - C#

new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)

Solution 9 - C#

Why not use EF6 attribute based e-mail validation?

As you can see above, Regex validation for e-mail always has some hole in it. If you are using EF6 data annotations, you can easily achieve reliable and stronger e-mail validation with EmailAddress data annotation attribute available for that. I had to remove the regex validation I used before for e-mail when I got mobile device specific regex failure on e-mail input field. When the data annotation attribute used for e-mail validation, the issue on mobile was resolved.

public class LoginViewModel
{
    [EmailAddress(ErrorMessage = "The email format is not valid")]
    public string Email{ get; set; }

Solution 10 - C#

Try this on for size:

public static bool IsValidEmailAddress(this string s)
{
    var regex = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    return regex.IsMatch(s);
}

Solution 11 - C#

This regex works perfectly:

bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z");
}

Solution 12 - C#

Email validation using regex

	string pattern = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
	
	//check first string
   if (Regex.IsMatch(EmailId1 , pattern))
   {	
	   //if email is valid
	    Console.WriteLine(EmailId1+ " is a valid Email address ");
   }

Source: https://qawithexperts.com/article/asp-net/email-address-validation-in-c-with-and-without-regex/240">email validation c#

Validation Without Regex using MailAddress.MailAddress(String) class constructor

public bool IsEmailValid(string emailaddress)
{
 try
 {
    MailAddress m = new MailAddress(emailaddress);
    return true;
 }
 catch (FormatException)
 {
    return false;
 }
}


Solution 13 - C#

Try this, it's working for me:

public bool IsValidEmailAddress(string s)
{
    if (string.IsNullOrEmpty(s))
        return false;
    else
    {
        var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        return regex.IsMatch(s) && !s.EndsWith(".");
    }
}

Solution 14 - C#

This one prevents invalid emails mentioned by others in the comments:

Abc.@example.com
Abc..123@example.com
name@hotmail
toms.email.@gmail.com
test@-online.com

It also prevents emails with double dots:

hello..world@example..com

Try testing it with as many invalid email addresses as you can find.

using System.Text.RegularExpressions;

public static bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
        && Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
}

See http://seaf-email.blogspot.com/p/code.html#csharp">validate email address using regular expression in C#.

Solution 15 - C#

As an update to the popular answer of Alex: In .NET 5 MailAddress now has a TryCreate. So you can do something like:

public static bool IsValidEmail(string email)
{
    if (!MailAddress.TryCreate(email, out var mailAddress))
        return false;

    // And if you want to be more strict:
    var hostParts = mailAddress.Host.Split('.');
    if (hostParts.Length == 1)
        return false; // No dot.
    if (hostParts.Any(p => p == string.Empty))
        return false; // Double dot.
    if (hostParts[^1].Length < 2)
        return false; // TLD only one letter.

    if (mailAddress.User.Contains(' '))
        return false;
    if (mailAddress.User.Split('.').Any(p => p == string.Empty))
        return false; // Double dot or dot at end of user part.

    return true;
}

Solution 16 - C#

It has taken many attempts to create an email validator which catches nearly all worldwide requirements for email.

Extension method you can call with:

myEmailString.IsValidEmailAddress();

Regex pattern string you can get by calling:

var myPattern = Regex.EmailPattern;

The Code (mostly comments):

    /// <summary>
    /// Validates the string is an Email Address...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddress(this string emailAddress)
    {
        var valid = true;
        var isnotblank = false;

        var email = emailAddress.Trim();
        if (email.Length > 0)
        {
            // Email Address Cannot start with period.
            // Name portion must be at least one character
            // In the Name, valid characters are:  a-z 0-9 ! # _ % & ' " = ` { } ~ - + * ? ^ | / $
            // Cannot have period immediately before @ sign.
            // Cannot have two @ symbols
            // In the domain, valid characters are: a-z 0-9 - .
            // Domain cannot start with a period or dash
            // Domain name must be 2 characters.. not more than 256 characters
            // Domain cannot end with a period or dash.
            // Domain must contain a period
            isnotblank = true;
            valid = Regex.IsMatch(email, Regex.EmailPattern, RegexOptions.IgnoreCase) &&
                !email.StartsWith("-") &&
                !email.StartsWith(".") &&
                !email.EndsWith(".") && 
                !email.Contains("..") &&
                !email.Contains(".@") &&
                !email.Contains("@.");
        }

        return (valid && isnotblank);
    }

    /// <summary>
    /// Validates the string is an Email Address or a delimited string of email addresses...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddressDelimitedList(this string emailAddress, char delimiter = ';')
    {
        var valid = true;
        var isnotblank = false;

        string[] emails = emailAddress.Split(delimiter);

        foreach (string e in emails)
        {
            var email = e.Trim();
            if (email.Length > 0 && valid) // if valid == false, no reason to continue checking
            {
                isnotblank = true;
                if (!email.IsValidEmailAddress())
                {
                    valid = false;
                }
            }
        }
        return (valid && isnotblank);
    }

    public class Regex
    {
        /// <summary>
        /// Set of Unicode Characters currently supported in the application for email, etc.
        /// </summary>
        public static readonly string UnicodeCharacters = "À-ÿ\p{L}\p{M}ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß"; // German and French

        /// <summary>
        /// Set of Symbol Characters currently supported in the application for email, etc.
        /// Needed if a client side validator is being used.
        /// Not needed if validation is done server side.
        /// The difference is due to subtle differences in Regex engines.
        /// </summary>
        public static readonly string SymbolCharacters = @"!#%&'""=`{}~\.\-\+\*\?\^\|\/\$";

        /// <summary>
        /// Regular Expression string pattern used to match an email address.
        /// The following characters will be supported anywhere in the email address:
        /// ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß[a - z][A - Z][0 - 9] _
        /// The following symbols will be supported in the first part of the email address(before the @ symbol):
        /// !#%&'"=`{}~.-+*?^|\/$
        /// Emails cannot start or end with periods,dashes or @.
        /// Emails cannot have two @ symbols.
        /// Emails must have an @ symbol followed later by a period.
        /// Emails cannot have a period before or after the @ symbol.
        /// </summary>
        public static readonly string EmailPattern = String.Format(
            @"^([\w{0}{2}])+@{1}[\w{0}]+([-.][\w{0}]+)*\.[\w{0}]+([-.][\w{0}]+)*$",                     //  @"^[{0}\w]+([-+.'][{0}\w]+)*@[{0}\w]+([-.][{0}\w]+)*\.[{0}\w]+([-.][{0}\w]+)*$",
            UnicodeCharacters,
            "{1}",
            SymbolCharacters
        );
    }

Solution 17 - C#

To validate your email ID, you can simply create such method and use it.

    public static bool IsValidEmail(string email)
    {
        var r = new Regex(@"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
        return !String.IsNullOrEmpty(email) && r.IsMatch(email);
    }

This will return True / False. (Valid / Invalid Email Id)

Solution 18 - C#

public static bool ValidateEmail(string str)
{                       
     return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}

I use the above code to validate the email address.

Solution 19 - C#

   public bool VailidateEntriesForAccount()
    {
       if (!(txtMailId.Text.Trim() == string.Empty))
        {
            if (!IsEmail(txtMailId.Text))
            {
                Logger.Debug("Entered invalid Email ID's");
                MessageBox.Show("Please enter valid Email Id's" );
                txtMailId.Focus();
                return false;
            }
        }
     }
   private bool IsEmail(string strEmail)
    {
        Regex validateEmail = new Regex("^[\\W]*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z] {2,4}[\\W]*,{1}[\\W]*)*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z]{2,4})[\\W]*$");
        return validateEmail.IsMatch(strEmail);
    }

Solution 20 - C#

string patternEmail = @"(?<email>\w+@\w+\.[a-z]{0,3})";
Regex regexEmail = new Regex(patternEmail);

Solution 21 - C#

This is my favorite approach to this so far:

public static class CommonExtensions
{
    public static bool IsValidEmail(this string thisEmail)
        => !string.IsNullOrWhiteSpace(thisEmail) &&
           new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").IsMatch(thisEmail);
}

Then use the created string extension like:

if (!emailAsString.IsValidEmail()) throw new Exception("Invalid Email");

Solution 22 - C#

There's no perfect regular expression, but this one is pretty strong, I think, based on study of RFC5322. And with C# string interpolation, pretty easy to follow, I think, as well.

const string atext = @"a-zA-Z\d!#\$%&'\*\+-/=\?\^_`\{\|\}~";
var localPart = $"[{atext}]+(\\.[{atext}]+)*";
var domain = $"[{atext}]+(\\.[{atext}]+)*";
Assert.That(() => EmailRegex = new Regex($"^{localPart}@{domain}$", Compiled), 
Throws.Nothing);

Vetted with NUnit 2.x.

Solution 23 - C#

Just let me know IF it doesn't work :)

public static bool isValidEmail(this string email)
{

    string[] mail = email.Split(new string[] { "@" }, StringSplitOptions.None);

    if (mail.Length != 2)
        return false;

    //check part before ...@

    if (mail[0].Length < 1)
        return false;

    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-\.]+$");
    if (!regex.IsMatch(mail[0]))
        return false;

    //check part after @...

    string[] domain = mail[1].Split(new string[] { "." }, StringSplitOptions.None);

    if (domain.Length < 2)
        return false;

    regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-]+$");

    foreach (string d in domain)
    {
        if (!regex.IsMatch(d))
            return false;
    }

    //get TLD
    if (domain[domain.Length - 1].Length < 2)
        return false;

    return true;

}

Solution 24 - C#

I've created a FormValidationUtils class to validate email:

public static class FormValidationUtils
{
    const string ValidEmailAddressPattern = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";

    public static bool IsEmailValid(string email)
    {
        var regex = new Regex(ValidEmailAddressPattern, RegexOptions.IgnoreCase);
        return regex.IsMatch(email);
    }
}

Solution 25 - C#

here is our Regex for this case:

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

there are three parts, which are checcked. the last one is propably the one you need. the specific term {2,6} indicates you the min/max length of the TLD at the end. HTH

Solution 26 - C#

Try the Following Code:

using System.Text.RegularExpressions;
if  (!Regex.IsMatch(txtEmail.Text, @"^[a-z,A-Z]{1,10}((-|.)\w+)*@\w+.\w{3}$"))
        MessageBox.Show("Not valid email.");

Solution 27 - C#

STRING SEARCH USING REGEX METHOD IN C#

How to validate an Email by Regular Expression?

string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
{
    Console.WriteLine("Email: {0} is valid.", Email);
}
else
{
    Console.WriteLine("Email: {0} is not valid.", Email);
}

Use Reference String.Regex() Method

Solution 28 - C#

1

^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$

2

^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

Solution 29 - C#

I think your caret and dollar sign are part of the problem You should also modify the regex a little, I use the next @"[ :]+([\w.-]+)@([\w-.])+((.(\w){2,3})+)"

Solution 30 - C#

Regex Email Pattern:

^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$

Solution 31 - C#

I've been using the Regex.IsMatch().

First of all you need to add the next statement:

using System.Text.RegularExpressions;

Then the method looks like:

private bool EmailValidation(string pEmail)
{
                 return Regex.IsMatch(pEmail,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}

It's a private method because of my logic but you can put the method as static in another Layer such as "Utilities" and call it from where you need.

Solution 32 - C#

Visual studio had this for years.

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Hope this helps!

Solution 33 - C#

This code will help to validate email id using regex expression in c#.Net..it is easy to use

if (!System.Text.RegularExpressions.Regex.IsMatch("<Email String Here>", @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
        {
            MessageBox.show("Incorrect Email Id.");
        }

Solution 34 - C#

A combination of the above responses. I would use the Microsoft preferred approach of using MailAddress but implement as an extension of string:

public static bool IsValidEmailAddress(this string emailaddress)
    {
        try
        {
            MailAddress m = new MailAddress(emailaddress);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }

Then just validate any string as an email address with:

string customerEmailAddress = "[email protected]";
customerEmailAddress.IsValidEmailAddress()

Clean simple and portable. Hope it helps someone. Regex for emails are messy.

That said MattSwanson has a blog on this very topic and he strongly suggests NOT using regexs and instead just check for '@' abd maybe a dot. Read his explanation here: https://mdswanson.com/blog/2013/10/14/how-not-to-validate-email-addresses.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergeyView Question on Stackoverflow
Solution 1 - C#AlexView Answer on Stackoverflow
Solution 2 - C#AvinashView Answer on Stackoverflow
Solution 3 - C#RhyousView Answer on Stackoverflow
Solution 4 - C#mr.baby123View Answer on Stackoverflow
Solution 5 - C#CodeArtistView Answer on Stackoverflow
Solution 6 - C#MaheepView Answer on Stackoverflow
Solution 7 - C#Tejas BagadeView Answer on Stackoverflow
Solution 8 - C#ClementView Answer on Stackoverflow
Solution 9 - C#Gemunu R WickremasingheView Answer on Stackoverflow
Solution 10 - C#camaincView Answer on Stackoverflow
Solution 11 - C#Luca ZieglerView Answer on Stackoverflow
Solution 12 - C#Vikas LalwaniView Answer on Stackoverflow
Solution 13 - C#Tarek El-MallahView Answer on Stackoverflow
Solution 14 - C#GeekView Answer on Stackoverflow
Solution 15 - C#Marcel WolterbeekView Answer on Stackoverflow
Solution 16 - C#Jason WilliamsView Answer on Stackoverflow
Solution 17 - C#Palak PatelView Answer on Stackoverflow
Solution 18 - C#RameshView Answer on Stackoverflow
Solution 19 - C#sindhu jampaniView Answer on Stackoverflow
Solution 20 - C#StefanL19View Answer on Stackoverflow
Solution 21 - C#Mariano PeinadorView Answer on Stackoverflow
Solution 22 - C#mwpowellhtxView Answer on Stackoverflow
Solution 23 - C#Roni ToviView Answer on Stackoverflow
Solution 24 - C#Waqar UlHaqView Answer on Stackoverflow
Solution 25 - C#GreenLionView Answer on Stackoverflow
Solution 26 - C#Leelu HalwanView Answer on Stackoverflow
Solution 27 - C#ManishView Answer on Stackoverflow
Solution 28 - C#Rae LeeView Answer on Stackoverflow
Solution 29 - C#ABMoharramView Answer on Stackoverflow
Solution 30 - C#GhanatView Answer on Stackoverflow
Solution 31 - C#GreatNewsView Answer on Stackoverflow
Solution 32 - C#Gonza OviedoView Answer on Stackoverflow
Solution 33 - C#RAVI VAGHELAView Answer on Stackoverflow
Solution 34 - C#ComeInView Answer on Stackoverflow