268

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 "something@someth.ing" email

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Sergey
  • 11,548
  • 24
  • 76
  • 113
  • 1
    Other than you're not including valid characters, as specified by the RFCs [5321](http://tools.ietf.org/html/rfc5321) & [5322](http://tools.ietf.org/html/rfc5322)--nothing. – Brad Christie Mar 17 '11 at 16:53
  • 2
    possible duplicate of [What is the best regular expression for validating email addresses?](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses) – RB. Mar 17 '11 at 16:53
  • I think _you_ have to tell us what's wrong and then others here can help you fixing the wrong thing. – Uwe Keim Mar 17 '11 at 16:53
  • p.s., it's not matching `something@some.thing` because the `.thing` doesn't fall under your last check (1+ groups of 2-3 characters, separated by periods). `thing` is 5 characters. – Brad Christie Mar 17 '11 at 16:56
  • 14
    You have a problem -> you think 'regex' -> now you have 2 problems ;-) – Jakub Konecki Mar 17 '11 at 19:03
  • what about `foo+bar@example.com` – Valerij Feb 05 '14 at 13:27
  • 2
    Just a comment about your regex. With these new .amsterdam, .info and other domains the regex should be:`@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,})+)$""` – Ton Snoei Jul 19 '17 at 05:43

37 Answers37

483

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.

Marcel Wolterbeek
  • 3,367
  • 36
  • 48
Alex
  • 6,228
  • 1
  • 22
  • 18
  • 83
    This didn't catch double dots ".." nor inline spaces ". ". I'll go with the regex instead – Benny Skogberg Feb 28 '12 at 15:27
  • 45
    Despite this is a popular answer. It is not right, fail to catch at least two invalid formats: "Abc.@example.com" , "Abc..123@example.com" – sean717 Aug 22 '12 at 05:22
  • 13
    @sean717: See the RFC and/or [link](http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx). I agree that your examples probably won't work in the real world, but that doesn't make them invalid. – Dan Pichelman Aug 27 '12 at 18:53
  • 13
    Whether it is working or not using try catch to validate input is not recommended practice. Regex is definitely better way to go. – mrt Oct 10 '12 at 11:00
  • 180
    -1 Bad piece of code. Catching an exception is not the way to validate fields. – ken2k Jan 11 '13 at 10:24
  • be aware that this does not check if it has a domain. So "test@mail" will pass – RClemens Jul 12 '21 at 12:20
  • Not the best code. it actually misses some invalid emails. – rufw91 Oct 07 '21 at 06:57
  • Is it good to use new instead of regex? I suppose not. –  Dec 27 '21 at 09:50
  • 1
    As Microsoft says: "If you try to create the perfect regular expression to validate that the structure of an email is correct, the expression becomes so complex that it's incredibly difficult to debug or improve. " Therefore thanks for your easy solution, outsourcing the check to Microsoft :-) https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format – K232 Mar 15 '22 at 08:28
  • Why would someone be allergic to allergic to try/catch? Are there any known downsides? – Vlad Radu Jun 02 '22 at 13:26
  • @Vlad Radu: When an exception is created, the stack trace and application state must be pushed on the stack, which takes quite some processing. Not a big problem if this occurs incidental, but if this happens often it can be a performance issue. And a lot of people consider using try/catch to validate fields as bad programming. – Marcel Wolterbeek Jun 05 '22 at 13:01
  • 1
    @MarcelWolterbeek I see. But this is why an Exception is called like it is. As long as it is generated only occasionally, I think it doesn't hurt much. So, I would use your answer for something out of the hot path. – Vlad Radu Jun 06 '22 at 15:15
120

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

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Avinash
  • 1,279
  • 1
  • 8
  • 3
91

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 an 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.

Rhyous
  • 6,510
  • 2
  • 44
  • 50
  • Thats the one I was looking for - thanx! Takes both double dots ".." and white spaces ". ". – Benny Skogberg Feb 28 '12 at 17:43
  • 7
    I updated my regular expression project to have unit tests and I even fixed a couple of bugs: C# – Email Regular Expression http://www.rhyous.com/2010/06/15/csharp-email-regular-expression – Rhyous Oct 16 '12 at 21:00
  • With the new TLDs, we maybe should replace [a-zA-Z]{2,4} in the third line with a {0} and then doing a string.format(pattern, pipeSeparatedAllowedTlds) where pipeSeparatedAllowedTlds would have to be created by iterating through this file: http://data.iana.org/TLD/tlds-alpha-by-domain.txt – Rhyous Feb 25 '14 at 22:54
  • 12
    Parth. Can you tell me what RFC rule is broken by your email? Because guess what. According to RFC, it is valid!!!! If you purchasesd the URL in.in, you could create this email address. Understand? – Rhyous May 09 '14 at 15:23
  • @Rhyous, this regex allows "john.doe@bob-.com" and "john.doe@-bob.com" as valid. Why? See https://dotnetfiddle.net/ml3NH8 – George Paoli Oct 26 '18 at 20:08
  • That is because I was more focussed on the RFC for emails and not the RFC for domain names. According to https://tools.ietf.org/html/rfc1035, a domain should start with a letter and end with a letter or number. So my regex should end with this: + @"(((([A-z]+([\-]*[A-z0-9]+))+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$"; – Rhyous Oct 26 '18 at 20:35
  • 2
    Actually, it looks like I already updated that on my github here: https://github.com/rhyous/EmailRegEx. However, \w may include underscores, so I may have to edit it for accuracy. – Rhyous Oct 26 '18 at 20:37
  • Here is valid address your Regex can't process `Dörte@Sörensen.example.com` – T.S. Apr 26 '19 at 18:32
  • @T.S. I put it in my unit tests and it passed. Still you should download the GitHub project and test it there. https://github.com/rhyous/EmailRegEx – Rhyous Apr 30 '19 at 14:38
  • @Rhyous is it worth altogether to hard-verify email addresses anymore? Just check that it has `@` and `.` and no spaces/dots on the sides. There is so much allowed in email, requirements/specs are very loose – T.S. Apr 30 '19 at 15:31
  • Perhaps you are looking at a limited use case. If you have a web site and registration uses email so the correct email is critical, most programs send a verification email. That is the best way to verify an email address. – Rhyous May 01 '19 at 00:24
  • @T.S. However, the UI has a different use case. It should notify a user if they enter an invalid email, such as if they forgot to type in .com, or copied it from somewhere and also copied junk text. There are more use cases, too. If you are reading unknown source data and you want to be 100% sure whether the data is a valid email and take action if it is, this is useful. – Rhyous May 01 '19 at 00:34
  • @Rhyous we receive json payload with bunch of info including emails. these could be from any part of the world. How can I check them so strict? We let it in fairly unrestricted. If people supplied it, or systems they supplied through have not done some form of verification (confirmation), then its their issue why our system can't send something. Plus, even valid email account can be abandoned or closed. What we can do, if we get mailer daemon, we can detect user and notify the source, "hey this account has bad email". – T.S. May 01 '19 at 15:24
  • 1
    First, checking to see if an email is RFC valid is different from checking if it is a *real* email address. - If the email in the JSON doesn't pass the RFC, don't try to send email to it, it is for sure not real. And can you reject the JSON with an invalid email response? - If it passes the RFC, it's possibly a *real* emal. You are forced to accept the JSON, then try to send mail to it. Be careful, though. Sending bad emails in mass can affect your mailer daemon. It can get your IP blacklisted, or if using a mail tool like MailChimp, get your account limited. – Rhyous May 01 '19 at 19:58
49

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@c@example.com
Invalid: Abc.example.com
Valid: j..s@proseware.com
Valid: j.@server1.proseware.com
Invalid: js*@proseware.com
Invalid: js@proseware..com
Valid: ma...ma@jjf.co
Valid: ma.@jjf.com
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: d.j@server1.proseware.com
Valid: david.jones@proseware.com
Valid: j.s@server1.proseware.com
Invalid: j@proseware.com9
Valid: j_9@[129.126.118.1]
Valid: jones@ms1.proseware.com
Invalid: js#internal@proseware.com
Invalid: js@proseware.com9
Invalid: js@proseware.com9
Valid: m.a@hostname.co
Valid: m_a1a@hostname.com
Valid: ma.h.saraf.onemore@hostname.com.edu
Valid: ma@hostname.com
Invalid: ma@hostname.comcom
Invalid: MA@hostname.coMCom
Valid: ma12@hostname.com
Valid: ma-a.aa@hostname.com.edu
Valid: ma-a@hostname.com
Valid: ma-a@hostname.com.edu
Valid: ma-a@1hostname.com
Valid: ma.a@1hostname.com
Valid: ma@1hostname.com
mr.baby123
  • 2,208
  • 23
  • 12
  • 1
    Doesn't match `[me]@whatever.museum` – Toto Dec 04 '12 at 14:11
  • Invalid: Abc.example.com YES, that works correctly, however, this "toms.email.@gmail.com"; does not work – Tom Stickel Jul 18 '13 at 08:06
  • 2
    Had to add a plus sign: ` @"^([\w-\.+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" ` 11 the char left on ] Google and hotmail aliassing allow for plus sign in first section before @ sign. – Henk J Meulekamp Aug 19 '13 at 07:52
  • This is the same as above. allowing "somename@gmail.com.in.in.in" as valid email address...!! – prem30488 May 09 '14 at 09:51
  • 13
    @ParthTrivedi Why do you insist that `somename@gmail.com.in.in.in` is not a valid email address? – Ivaylo Slavov Jul 17 '15 at 09:45
  • It did not validate arvtest26Aug2021+2@gmail.com. One answer suggested by Tarek El-Mallah is better – Arvind Krmar Aug 26 '21 at 13:39
21

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);
}
CodeArtist
  • 5,534
  • 8
  • 40
  • 65
  • 1
    This should be the best regex because it seems to validate RFCs 5321 and 5322. It miss some unit testing. – ToXinE Jul 20 '18 at 16:17
  • 1
    Does not capture dot at the end of the email address. – Sellorio Jan 20 '19 at 00:13
  • Solution is elegant to adapt and the Regex covers wide range of valid / invalid evaluations, but it doesn't cover all the Email Address validation unit tests available here: https://codefool.tumblr.com/post/15288874550/list-of-valid-and-invalid-email-addresses – cusman Aug 31 '20 at 14:38
  • Be warned that naively using this answer as-is will create a new Regex every time - you must store it in another static variable (like the referenced MS data annotations code does) or suffer a massive performance hit. eg `private static Regex _emailRegex = EmailValidation();` – notracs Aug 23 '23 at 05:12
16

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));
}
Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108
Maheep
  • 5,539
  • 3
  • 28
  • 47
  • 1
    this expression doesn't match valid addresses `!#$%&'*+-/=?^_`.{|}~@example.com` or this one `Dörte@Sörensen.example.com` – T.S. Apr 26 '19 at 20:23
  • This works!! Remove the white spaces once you copy and paste the regex. @"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w] *[0-9a-zA-Z]*\.)+[a-zA-Z]{2,})$" – Pavitha May 24 '23 at 00:51
12

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);
Tejas Bagade
  • 163
  • 1
  • 4
12

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;
}
Marcel Wolterbeek
  • 3,367
  • 36
  • 48
9

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; }
9
new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)
Clement
  • 3,990
  • 4
  • 43
  • 44
  • The issue I have with C# default EmailAddress validations is that they accept abc@de as a valid email even though there's no TLD provided. Do you have any solution for that? – Reza Taba Dec 05 '22 at 17:04
  • @Reza Taba - I believe the answer to your question is found here: https://stackoverflow.com/questions/20573488/why-does-html5-form-validation-allow-emails-without-a-dot – StackOverflowUser Apr 30 '23 at 04:44
7

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);
}
camainc
  • 3,750
  • 7
  • 35
  • 46
6

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");
}
Luca Ziegler
  • 3,236
  • 1
  • 22
  • 39
6

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: 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;
 }
}
Vikas Lalwani
  • 1,041
  • 18
  • 29
  • This will not match `me@localhost`. Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Apr 27 '20 at 12:33
5

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(".");
    }
}
Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
Tarek El-Mallah
  • 4,015
  • 1
  • 31
  • 46
5

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 validate email address using regular expression in C#.

Geek
  • 413
  • 6
  • 4
  • This returns false for all of my invalid email addresses. Unfortunately, also returns false for many valid email addresses. – Mark Jul 13 '18 at 13:41
4

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)

Palak Patel
  • 235
  • 2
  • 6
2

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
        );
    }
Jason Williams
  • 2,740
  • 28
  • 36
1
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.

Ramesh
  • 392
  • 1
  • 12
  • 39
1
   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);
    }
sindhu jampani
  • 504
  • 3
  • 10
  • 30
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value – AStopher Aug 02 '18 at 10:49
1

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");
Mariano Peinador
  • 630
  • 9
  • 14
1

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.

mwpowellhtx
  • 351
  • 1
  • 9
1

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;

}
Roni Tovi
  • 828
  • 10
  • 21
1

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);
    }
}
Waqar UlHaq
  • 6,144
  • 2
  • 34
  • 42
0

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.");
chopper
  • 6,649
  • 7
  • 36
  • 53
0

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

dub stylee
  • 3,252
  • 5
  • 38
  • 59
Manish
  • 1
  • 1
0
string patternEmail = @"(?<email>\w+@\w+\.[a-z]{0,3})";
Regex regexEmail = new Regex(patternEmail);
StefanL19
  • 1,476
  • 2
  • 14
  • 29
0

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,}))$
Rae Lee
  • 1,321
  • 10
  • 11
0

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})+)"

0

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])\\]))$
Bugs
  • 4,491
  • 9
  • 32
  • 41
Ghanat
  • 158
  • 1
  • 11
0

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.

GreatNews
  • 575
  • 5
  • 13
0

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

GreenLion
  • 19
  • 1
  • 3
0

I use:

public bool ValidateEmail(string email)
{
   Regex 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])?$");
   if (regex.IsMatch(email))
      return true;

     return false;
}
Yudner
  • 533
  • 4
  • 9
0

Here is my solution after gathering info from here and Microsoft documents:

/// <summary>
/// * TLD support from 2 to 5 chars (modify the values as you want)
/// * Supports: abc@gmail.com.us
/// * Non-sensitive case 
/// * Stops operation if takes longer than 250ms and throw a detailed exception
/// </summary>
/// <param name="email"></param>
/// <returns>valid: true | invalid: false </returns>
/// <exception cref="ArgumentException"></exception>

private bool validateEmailPattern(string email) {
    try {
        return Regex.IsMatch(email,
            @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,5})+)$",
            RegexOptions.None, TimeSpan.FromMilliseconds(250));
    } catch (RegexMatchTimeoutException) {
        // throw an exception explaining the task was failed 
        _ = email ?? throw new ArgumentException("email, Timeout/failed regexr processing.", nameof(email));
    }
}
Reza Taba
  • 1,151
  • 11
  • 15
0

At the moment for me the best approach is to use the FluentValidation library. It has a built-in validator for the email address. Usage is very simple and you don't have to think about regex.

using FluentValidation;
public class TestClass
{
   public string Email { get; set; }
}

public class TestClassValidator: AbstractValidator<TestClass>
{
   public TestClassValidator()
   {            
      RuleFor(x => x.Email).EmailAddress().WithMessage($"nameof{(TestClass.Email)} is not a valid email address");
   }
}

I realize the question was asked a long time ago, but maybe refreshing the answer with a newer approach will help someone.

MKasprzyk
  • 503
  • 5
  • 17
-2

Visual studio had this for years.

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

Hope this helps!

Gonza Oviedo
  • 1,312
  • 15
  • 20
  • 3
    There are 19 non alpha-numeric characters valid for email addresses. This regex will fail on 15 of them. It will also allow emails which begin or end with periods or dashes or have periods or dashes before or after the @. – Jason Williams Dec 04 '14 at 22:51
-3

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.");
        }
RAVI VAGHELA
  • 877
  • 1
  • 10
  • 12
  • 1
    Please explain what your code does and why it will solve the problem. An answer that just contains code (even if it's working) usually wont help the OP to understand their problem. – SuperBiasedMan Jul 15 '15 at 12:28
  • Hi @SuperBiasedMan it is a code to validate email for c#.net which already mentioned above the code. It is for C# language not for python. so dont down any ones answer without understanding or just for fun... – RAVI VAGHELA May 27 '17 at 11:28
-5

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 = "bert@potato.com";
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

ComeIn
  • 1,519
  • 17
  • 12
  • This didn't catch double dots ".." nor inline spaces ". ". I'll go with the regex instead – Offir Nov 08 '16 at 13:52
  • 1
    Catching an exception is not validation ... Huge overhead relating to stack trace building mechanisms etc... – Sharique Abdullah Apr 25 '17 at 13:40
  • @ShariqueAbdullah Minimal overheads and much more readable than regex. Will improve as the Mail API improves. As mentioned this is the Microsoft Approved approach, maybe argue with them. Validation by exception handling is very much an accepted method of validation, many mainstream frameworks use this very approach. – ComeIn Apr 28 '17 at 02:20
  • @OffirPe'er According to Matt Swanson, using regex to validate emails is bad practice. https://mdswanson.com/blog/2013/10/14/how-not-to-validate-email-addresses.html – ComeIn Jun 01 '17 at 23:47