46

I have seen a multitude of regular expressions for different programming languages that all purport to validate email addresses. I have seen many comments saying that the expressions in question do not work for certain cases and that they are either too strict or too permissive. What I'm looking for is a regular expression that I can use in my C# code that is definitive.

The best thing I have found is this

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

Is there something better?

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • I don't know too much on the topic, but i've read throughout SO that you SHOULDN'T use regex for email validation. – Kestami Apr 23 '13 at 11:18
  • http://ex-parrot.com/~pdw/Mail-RFC822-Address.html – Pavel Anossov Apr 23 '13 at 11:19
  • 3
    Do not regex email addresses. Send a confirmation email to verify their email address is correct. – Dustin Kingen Apr 23 '13 at 11:21
  • That regex actually fails a valid email address. So, you definitely need something better. Sorry, I don't know of any. – Colin Mackay Apr 23 '13 at 11:22
  • *Is there something better?*: If you mean something that actually works, then yes. The regex you posted will not match a wide range of valid email addresses. – sloth Apr 23 '13 at 11:22
  • 1
    There is no definitive validation for email addresses for any situation. Any pattern will either be too strict or too permissive in differernt situations. You simply have to pick one pattern that validates what you need in each separate situation. Even a pattern that follows the RFC standard is too strict in some situations, as it won't allow some email addresses that are actually in use. – Guffa Apr 23 '13 at 11:30
  • Here is a better solution directly from our friends at Microsoft: https://msdn.microsoft.com/en-us/library/01escwtf%28v=vs.110%29.aspx – Amit Mittal Jun 27 '15 at 07:23
  • The question specified as original is for php. The regex syntax for different languages are different, so this question is not a duplicate of php question. However the question should be closed as a duplicate of [Regex Email validation](//stackoverflow.com/q/5342375) (C#) – Michael Freidgeim Jul 25 '17 at 12:39
  • This is not a duplicate - C# regexes are a slightly different flavour to php and the referenced SO question cannot be used directly in C# – David Clarke Sep 18 '17 at 01:55

6 Answers6

172

Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.

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

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);
mafafu
  • 1,226
  • 1
  • 17
  • 22
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
23

First option (bad because of throw-catch, but MS will do work for you):

bool IsValidEmail(string email)
{
    try {
        var mail = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch {
        return false;
    }
}

Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • 15
    -1 `System.Net.Mail.MailAddress` approves way too many address combinations that would fail in reality and are also wrong according to the RFC spec, such as `unescaped white space@fake$com`. – Doug S May 24 '14 at 21:04
  • 3
    If the purpose here is to send a mail with `System.Net`, then this validation is adequate – JDandChips Aug 19 '14 at 14:29
  • 1
    @VinayakPrabha above code probably outdated from 2013. The new domains were introduced and I don't know if Microsoft included them – Piotr Stapp Mar 02 '16 at 19:49
  • agreed. The regex in the below line covers the new domains http://stackoverflow.com/questions/16167983/best-regular-expression-for-email-validation-in-c-sharp – VPP Mar 03 '16 at 14:31
  • if you pass "JB@hotmailcom" it will return true :( – Reza Sep 08 '16 at 19:16
  • I like to add some basic extra checks like `if (email.Host.EndsWith(".cmo")) { return false; }` and `if (!email.Host.Contains(".")) { return false; }` – Simon_Weaver Feb 10 '17 at 00:21
  • `MailAddress` sees whitespace as an e-mail address boundary, accepts repeating periods (..) and does not require TLD. Tried it and discarded this method. – Henk van Boeijen Feb 09 '21 at 17:33
15

This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.

public static bool isValidEmail(string inputEmail)
{
   string strRegex = @"^([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})(\]?)$";
   Regex re = new Regex(strRegex);
   if (re.IsMatch(inputEmail))
    return (true);
   else
    return (false);
}
Obama
  • 2,586
  • 2
  • 30
  • 49
4

Updated answer for 2019.

Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.

public static 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);

public static bool IsValidEmailFormat(string emailInput)
{
    return _regex.IsMatch(emailInput);
}

Alternative Configuration for Regex:

public static 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.Compiled);

I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.

Thread Safety And Regex
Regex Best Practices

HouseCat
  • 1,559
  • 20
  • 22
2

I would like to suggest new EmailAddressAttribute().IsValid(emailTxt) for additional validation before/after validating using RegEx

Remember EmailAddressAttribute is part of System.ComponentModel.DataAnnotations namespace.

jitin14
  • 144
  • 5
  • +1. If you absolutely need a regular expression, consider `^[^@]+@[^@]+$`, which is approximate to the algorithm EmailAddressAttribute uses. Internally, EmailAddressAttribute used regular expressions up until .NET 4.7.2, when it disabled them to reduce the number of places potentially vulnerable to a ReDoS attack (https://github.com/Microsoft/dotnet/blob/master/Documentation/compatibility/aspnet-472-compat-doc.md). Otherwise, the best way to validate an email address is to send an email to that address. – Jeremy Frey Sep 15 '22 at 15:51
0

Email Validation Regex

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$

Or

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$

Demo Link:

https://regex101.com/r/kN4nJ0/53

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 1
    "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com is a valid email address according to RFC and does not match your regex – JoelBonetR May 28 '18 at 16:25
  • Chinese characters are also valid, but I don't see any solutions here that take account of that ;) perhaps you will create one for us? See you in 6 years. – Kev Oct 02 '19 at 15:19