C# code to validate email address

C#EmailEmail Validation

C# Problem Overview


What is the most elegant code to validate that a string is a valid email address?

C# Solutions


Solution 1 - C#

What about this?

bool IsValidEmail(string email)
{
    var trimmedEmail = email.Trim();

    if (trimmedEmail.EndsWith(".")) {
        return false; // suggested by @TK-421
    }
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == trimmedEmail;
    }
    catch {
        return false;
    }
}

Per Stuart's comment, this compares the final address with the original string instead of always returning true. MailAddress tries to parse a string with spaces into "Display Name" and "Address" portions, so the original version was returning false positives.


To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.

Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:

  • cog@wheel
  • "cogwheel the orange"@example.com
  • 123@$.xyz

For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.

Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow  as an email address."


As for using exception handling for business logic, I agree that is a thing to be avoided. But this is one of those cases where the convenience and clarity may outweigh the dogma.

Besides, if you do anything else with the e-mail address, it's probably going to involve turning it to a MailAddress. Even if you don't use this exact function, you will probably want to use the same pattern. You can also check for specific kinds of failure by catching different exceptions: null, empty, or invalid format.


--- Further reading ---

Documentation for System.Net.Mail.MailAddress

Explanation of what makes up a valid email address

Solution 2 - C#

This is an old question, but all the answers I've found on SO, including more recent ones, are answered similarly to this one. However, in .Net 4.5 / MVC 4 you can add email address validation to a form by adding the [EmailAddress] annotation from System.ComponentModel.DataAnnotations, so I was wondering why I couldn't just use the built-in functionality from .Net in general.

This seems to work, and seems to me to be fairly elegant:

using System.ComponentModel.DataAnnotations;

class ValidateSomeEmails
{
    static void Main(string[] args)
    {
        var email = new EmailAddressAttribute();
        email.IsValid("[email protected]");         //true
        email.IsValid("[email protected]");       //true
        email.IsValid("[email protected]");     //true
        email.IsValid("[email protected]");      //true
        
        email.IsValid("fdsa");                          //false
        email.IsValid("fdsa@");                         //false
        email.IsValid("fdsa@fdsa");                     //false
        email.IsValid("fdsa@fdsa.");                    //false

        //one-liner
        if (new EmailAddressAttribute().IsValid("[email protected]")) 
            return true;
    }
}

Solution 3 - C#

I use this single liner method which does the work for me-

using System.ComponentModel.DataAnnotations;
public bool IsValidEmail(string source)
{
    return new EmailAddressAttribute().IsValid(source);
}

Per the comments, this will "fail" if the source (the email address) is null.

public static bool IsValidEmailAddress(this string address) => address != null && new EmailAddressAttribute().IsValid(address);

Solution 4 - C#

.net 4.5 added System.ComponentModel.DataAnnotations.EmailAddressAttribute

You can browse the EmailAddressAttribute's source, this is the Regex it uses internally:

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])))\.?$";

Solution 5 - C#

I took Phil's answer from #1 and created this class. Call it like this: bool isValid = Validator.EmailIsValid(emailString);

Here is the class:

using System.Text.RegularExpressions;

public static class Validator
{

    static Regex ValidEmailRegex = CreateValidEmailRegex();

    /// <summary>
    /// Taken from http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
    /// </summary>
    /// <returns></returns>
    private static Regex CreateValidEmailRegex()
    {
        string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
            + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
            + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";

        return new Regex(validEmailPattern, RegexOptions.IgnoreCase);
    }

    internal static bool EmailIsValid(string emailAddress)
    {
        bool isValid = ValidEmailRegex.IsMatch(emailAddress);

        return isValid;
    }
}

Solution 6 - C#

Personally, I would say that you should just make sure there is an @ symbol in there, with possibly a . character. There's many regexes you could use of varying correctness, but I think most of these leave out valid email addresses, or let invalid ones through. If people want to put in a fake email address, they will put in a fake one. If you need to verify that the email address is legit, and that the person is in control of that email address, then you will need to send them an email with a special coded link so they can verify that it indeed is a real address.

Solution 7 - C#

Short and accurate code

string Email = txtEmail.Text;
if (Email.IsValidEmail())
{
   //use code here 
}

public static bool IsValidEmail(this string email)
{
  string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";    
  var regex = new Regex(pattern, RegexOptions.IgnoreCase);    
  return regex.IsMatch(email);
}

Solution 8 - C#

I think the best way is as follow:

    public static bool EmailIsValid(string email)
    {
        string expression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

        if (Regex.IsMatch(email, expression))
        {
            if (Regex.Replace(email, expression, string.Empty).Length == 0)
            {
                return true;
            }
        }
        return false;
    }

You can have this static function in a general class.

Solution 9 - C#

The most elegant way is to use .Net's built in methods.

These methods:

  • Are tried and tested. These methods are used in my own professional projects.

  • Use regular expressions internally, which are reliable and fast.

  • Made by Microsoft for C#. There's no need to reinvent the wheel.

  • Return a bool result. True means the email is valid.

For users of .Net 4.5 and greater

Add this Reference to your project:

> System.ComponentModel.DataAnnotations

Now you can use the following code:

(new EmailAddressAttribute().IsValid("[email protected]"));

Example of use

Here are some methods to declare:

protected List<string> GetRecipients() // Gets recipients from TextBox named `TxtRecipients`
{
    List<string> MethodResult = null;

    try
    {
        List<string> Recipients = TxtRecipients.Text.Replace(",",";").Replace(" ", "").Split(';').ToList();

        List<string> RecipientsCleaned = new List<string>();

        foreach (string Recipient in RecipientsCleaned)
        {
            if (!String.IsNullOrWhiteSpace(Recipient))
            {
                RecipientsNoBlanks.Add(Recipient);

            }

        }

        MethodResult = RecipientsNoBlanks;

    }
    catch//(Exception ex)
    {
        //ex.HandleException();
    }

    return MethodResult;

}


public static bool IsValidEmailAddresses(List<string> recipients)
{
    List<string> InvalidAddresses = GetInvalidEmailAddresses(recipients);

    return InvalidAddresses != null && InvalidAddresses.Count == 0;

}

public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
    List<string> MethodResult = null;

    try
    {
        List<string> InvalidEmailAddresses = new List<string>();

        foreach (string Recipient in recipients)
        {
            if (!(new EmailAddressAttribute().IsValid(Recipient)) && !InvalidEmailAddresses.Contains(Recipient))
            {
                InvalidEmailAddresses.Add(Recipient);

            }

        }

        MethodResult = InvalidEmailAddresses;

    }
    catch//(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

...and code demonstrating them in action:

List<string> Recipients = GetRecipients();

bool IsValidEmailAddresses = IsValidEmailAddresses(Recipients);
            
if (IsValidEmailAddresses)
{
    //Emails are valid. Your code here

}
else
{
    StringBuilder sb = new StringBuilder();

    sb.Append("The following addresses are invalid:");

    List<string> InvalidEmails = GetInvalidEmailAddresses(Recipients);

    foreach (string InvalidEmail in InvalidEmails)
    {
        sb.Append("\n" + InvalidEmail);

    }

    MessageBox.Show(sb.ToString());

}

In addition, this example:

  • Extends beyond the spec since a single string is used to contain 0, one or many email addresses sperated by a semi-colon ;.
  • Clearly demonstrates how to use the IsValid method of the EmailAddressAttribute object.

Alternative, for users of a version of .Net less than 4.5

For situations where .Net 4.5 is not available, I use the following solution:

Specifically, I use:

public static bool IsValidEmailAddress(string emailAddress)
{
    bool MethodResult = false;

    try
    {
        MailAddress m = new MailAddress(emailAddress);

        MethodResult = m.Address == emailAddress;

    }
    catch //(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
    List<string> MethodResult = null;

    try
    {
        List<string> InvalidEmailAddresses = new List<string>();

        foreach (string Recipient in recipients)
        {
            if (!IsValidEmail(Recipient) && !InvalidEmailAddresses.Contains(Recipient))
            {
                InvalidEmailAddresses.Add(Recipient);

            }

        }

        MethodResult = InvalidEmailAddresses;

    }
    catch //(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

Solution 10 - C#

To be honest, in production code, the best I do is check for an @ symbol.

I'm never in a place to be completely validating emails. You know how I see if it was really valid? If it got sent. If it didn't, it's bad, if it did, life's good. That's all I need to know.

Solution 11 - C#

I find this regex to be a good trade off between checking for something more than just the @ mark, and accepting weird edge cases:

^[^@\s]+@[^@\s]+(\.[^@\s]+)+$

It will at least make you put something around the @ mark, and put at least a normal looking domain.

Solution 12 - C#

Email address validation is not as easy as it might seem. It's actually theoretically impossible to fully validate an email address using just a regular expression.

Check out my blog post about it for a discussion on the subject and a F# implementation using FParsec. [/shameless_plug]

Solution 13 - C#

I just want to point out, that there has been a recent addition to the .NET documentation regarding email validation, also utilitzing Regex operations. A thorough explanation to their implementation can be found there.

https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

For convenience, here is a list of their test results:

//       Valid: david.jones@proseware.com
//       Valid: d.j@server1.proseware.com
//       Valid: jones@ms1.proseware.com
//       Invalid: j.@server1.proseware.com
//       Valid: j@proseware.com9
//       Valid: js#internal@proseware.com
//       Valid: j_9@[129.126.118.1]
//       Invalid: j..s@proseware.com
//       Invalid: js*@proseware.com
//       Invalid: js@proseware..com
//       Valid: js@proseware.com9
//       Valid: j.s@server1.proseware.com
//       Valid: "j\"s\""@proseware.com
//       Valid: js@contoso.中国

Solution 14 - C#

Here's my answer -- Phil's solution fails for single letter domains like "[email protected]". Believe it or not, that's used =) (goes to centurylink, for instance).

Phil's answer is also going to work only with PCRE standard... so C# will take it, but javascript is going to bomb. It's too complex for javascript. So you can't use Phil's solution for mvc validation attributes.

Here's my regex. It'll work nicely with MVC validation attributes.

  • Everything before the @ is simplified, so that at least javascript will work. I'm okay relaxing validation here as long as exchange server doesn't give me a 5.1.3.

  • Everything after the @ is Phil's solution modified for single letter domains.

    public const string EmailPattern = @"^\s*[\w-+']+(.[\w-+']+)@A-Za-z0-9?.[A-Za-z][A-Za-z.][A-Za-z]$";

For people suggesting using system.net.mail MailMessage(), that thing is WAY to flexible. Sure, C# will accept the email, but then exchange server will bomb with 5.1.3 runtime error as soon as you try to send the email.

Solution 15 - C#

As mentioned in many answers, the domain of email addresses is complex. I would strongly discourage the use of a regex in this case. Those who match (most) cases are extremely complex to read and therefor to maintain. Furthermore, the still have difficulties supporting all cases, and are slow.

Microsoft's EmailAddress class helps a bit in that respect, but is not perfect either, I would argue. For an open source project I gave it try some years ago, by using a customized EmailParser.

That is used in [EmailAddress]https://github.com/Qowaiv/Qowaiv/blob/master/src/Qowaiv/EmailAddress.cs).

By using this approach, you're not only to validate email addresses, but also by cleaning out multiple formats of display names, getting rid of the mailto:-prefix, and normalizing domain literals based on IP-addresses, and lowercasing everything (note that the local part officially is case sensitive).

Scenario's your solution should support (and the mentioned one does):

[TestCase(null)]
[TestCase("")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("ab@sd@dd")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("ab@[188.120.150.10")]
[TestCase("[email protected]]")]
[TestCase("ab@[188.120.150.10].com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected].")]
[TestCase("ab@b+de.cc")]
[TestCase("[email protected]")]
[TestCase("[email protected],")]
[TestCase("plainaddress")]
[TestCase("plain.address")]
[TestCase("@%^%#$@#$@#.com")]
[TestCase("@domain.com")]
[TestCase("Joe Smith &lt;[email protected]&gt;")]
[TestCase("email.domain.com")]
[TestCase("email@[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected].")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("email@[123.123.123.123")]
[TestCase("email@[123.123.123].123")]
[TestCase("[email protected]]")]
[TestCase("[email protected].[123.123]")]
[TestCase("email@{leftbracket.com")]
[TestCase("email@rightbracket}.com")]
[TestCase("email@p|pe.com")]
[TestCase("isis@100%.nl")]
[TestCase("email@dollar$.com")]
[TestCase("email@r&amp;d.com")]
[TestCase("email@#hash.com")]
[TestCase("email@wave~tilde.com")]
[TestCase("email@exclamation!mark.com")]
[TestCase("email@question?mark.com")]
[TestCase("email@obelix*asterisk.com")]
[TestCase("email@grave`accent.com")]
[TestCase("email@colon:colon.com")]
[TestCase("email@caret^xor.com")]
[TestCase("email@=qowaiv.com")]
[TestCase("email@plus+.com")]
[TestCase("[email protected]>")]
[TestCase("email( (nested) )@plus.com")]
[TestCase("email)mirror(@plus.com")]
[TestCase("[email protected] (not closed comment")]
[TestCase("email(with @ in comment)plus.com")]
[TestCase(@"""Joe Smith [email protected]")]
[TestCase(@"""Joe Smith' [email protected]")]
[TestCase(@"""Joe Smith""[email protected]")]
[TestCase("email@mailto:domain.com")]
[TestCase("mailto:mailto:[email protected]")]
[TestCase("Display Name <[email protected]> (after name with display)")]
[TestCase("ReDoSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")]
public void IsInvalid(string email)
{
	Assert.IsFalse(EmailAddress.IsValid(email), email);
}

[TestCase("w@com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("ab@[120.254.254.120]")]
[TestCase("local@2001:0db8:85a3:0000:0000:8a2e:0370:7334")]
[TestCase("local@[2001:0db8:85a3:0000:0000:8a2e:0370:7334]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("email@domain")]
[TestCase("あいうえお@domain.com")]
[TestCase("local@あいうえお.com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("email@[123.123.123.123]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("{local{name{{with{@leftbracket.com")]
[TestCase("}local}name}}with{@rightbracket.com")]
[TestCase("|local||name|with|@pipe.com")]
[TestCase("%local%%name%with%@percentage.com")]
[TestCase("[email protected]")]
[TestCase("&local&&name&with&[email protected]")]
[TestCase("#local##name#with#@hash.com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("*local**name*with*@asterisk.com")]
[TestCase("`local``name`with`@grave-accent.com")]
[TestCase("^local^^name^with^@xor.com")]
[TestCase("[email protected]")]
[TestCase("[email protected]")]
[TestCase("Joe Smith <[email protected]>")]
[TestCase("[email protected] (joe Smith)")]
[TestCase(@"""Joe Smith"" [email protected]")]
[TestCase(@"""Joe\\tSmith"" [email protected]")]
[TestCase(@"""Joe\""Smith"" [email protected]")]
[TestCase(@"Test |<gaaf <[email protected]>")]
[TestCase("MailTo:[email protected]")]
[TestCase("mailto:[email protected]")]
[TestCase("Joe Smith <mailto:[email protected]>")]
[TestCase("Joe Smith <mailto:email(with comment)@domain.com>")]
[TestCase(@"""With extra < within quotes"" Display Name<[email protected]>")]
[TestCase("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")]
public void IsValid(string email)
{
	Assert.IsTrue(EmailAddress.IsValid(email), email);
}

Solution 16 - C#

I summarize all the above answers as of the current year 2021 I wrote for myself this class:

public static class StringExt {
	private const string emailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" 
			+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" 
			+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";

	public static bool IsValidMailAddress(this string pThis) 
			=> pThis is not null 
			&& Regex.IsMatch(pThis, emailPattern, RegexOptions.IgnoreCase);
}

Solution 17 - C#

If you really and I mean really want to know if an email address is valid...ask the mail exchanger to prove it, no regex needed. I can provide the code if requested.

General steps are as follows:

  1. does email address have a domain name part? (index of @ > 0)
  2. using a DNS query ask if domain has a mail exchanger
  3. open tcp connection to mail exchanger
  4. using the smtp protocol, open a message to the server using the email address as the reciever
  5. parse the server's response.
  6. quit the message if you made it this far, everything is good.

This is as you can imagine, very expensive time wise and relies on smtp, but it does work.

Solution 18 - C#

Generally speaking, a regular expression to validate email addresses is not an easy thing to come up with; at the time of this writing, the syntax of an email address must follow a relatively high number of standards and implementing all of them within a regular expression is practically unfeasible!

I highly suggest you to try our EmailVerify.NET, a mature .NET library which can validate email addresses following all of the current IETF standards (RFC 1123, RFC 2821, RFC 2822, RFC 3696, RFC 4291, RFC 5321 and RFC 5322), tests the related DNS records, checks if the target mailboxes can accept messages and can even tell if a given address is disposable or not.

Disclaimer: I am the lead developer for this component.

Solution 19 - C#

For the simple email like [email protected], below code is sufficient. 

 public static bool ValidateEmail(string email)
        {
            System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            System.Text.RegularExpressions.Match emailMatch = emailRegex.Match(email);
            return emailMatch.Success;
        }

Solution 20 - C#

In case you are using FluentValidation you could write something as simple as this:

public cass User
{
    public string Email { get; set; }
}

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(x => x.Email).EmailAddress().WithMessage("The text entered is not a valid email address.");
    }
}

// Validates an user. 
var validationResult = new UserValidator().Validate(new User { Email = "açflkdj" });

// This will return false, since the user email is not valid.
bool userIsValid = validationResult.IsValid;

Solution 21 - C#

a little modification to @Cogwheel answer

public static bool IsValidEmail(this string email)
{
  // skip the exception & return early if possible
  if (email.IndexOf("@") <= 0) return false;

  try
  {
    var address = new MailAddress(email);
    return address.Address == email;
  }
  catch
  {
    return false;
  }
}

Solution 22 - C#

There are a lot of strong answers here. However, I recommend that we take a step back. @Cogwheel answers the question https://stackoverflow.com/a/1374644/388267. Nevertheless, it could be costly in a bulk validation scenario, if many of the email address being validated are invalid. I suggest that we employ a bit of logic before we enter into his try-catch block. I know that the following code could be written using RegEx but that could be costly for new developers to understand. This is my twopence worth:

    public static bool IsEmail(this string input)
    {
        if (string.IsNullOrWhiteSpace(input)) return false;

        // MUST CONTAIN ONE AND ONLY ONE @
        var atCount = input.Count(c => c == '@');
        if (atCount != 1) return false;

        // MUST CONTAIN PERIOD
        if (!input.Contains(".")) return false;

        // @ MUST OCCUR BEFORE LAST PERIOD
        var indexOfAt = input.IndexOf("@", StringComparison.Ordinal);
        var lastIndexOfPeriod = input.LastIndexOf(".", StringComparison.Ordinal);
        var atBeforeLastPeriod = lastIndexOfPeriod > indexOfAt;
        if (!atBeforeLastPeriod) return false;

        // CODE FROM COGWHEEL'S ANSWER: https://stackoverflow.com/a/1374644/388267 
        try
        {
            var addr = new System.Net.Mail.MailAddress(input);
            return addr.Address == input;
        }
        catch
        {
            return false;
        }
    }

Solution 23 - C#

The most voted answer from @Cogwheel is best answer however i have tried to implement trim() string method so it will trim all user white space from string start to end. Check the code bellow for full example-

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

Solution 24 - C#

Another Regex Match answer :

   /// <summary>
   /// Validates the email input
   /// </summary>
   internal static bool ValidateEmail(string _emailAddress)
   { 
        
        string _regexPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
                + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

        return (string.IsNullOrEmpty(_emailAddress) == false && System.Text.RegularExpressions.Regex.IsMatch(_emailAddress, _regexPattern))
            ? true
            : false;
    }

Solution 25 - C#

private static bool IsValidEmail(string emailAddress)
{
    const string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
                                     + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
                                     + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";

    return new Regex(validEmailPattern, RegexOptions.IgnoreCase).IsMatch(emailAddress);
}

Solution 26 - C#

Check email string is right format or wrong format by System.Text.RegularExpressions:

    public static bool IsValidEmailId(string InputEmail)
    {
        Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        Match match = regex.Match(InputEmail);
        if (match.Success)
            return true;
        else
            return false;
    }

    protected void Email_TextChanged(object sender, EventArgs e)
    {
        String UserEmail = Email.Text;
        if (IsValidEmailId(UserEmail))
        {
            Label4.Text = "This email is correct formate";
        }
        else
        {
            Label4.Text = "This email isn't correct formate";
        }
    }

Solution 27 - C#

/Using the Internal Regex used in creating the "new EmailAddressAttribute();" component in .Net4.5 >>> using System.ComponentModel.DataAnnotations; //To Validate an Email Address......Tested and Working.

public bool IsEmail(string email)
{
    if (String.IsNullOrEmpty(email))
    {   return false;  }
    try
    {
        Regex _regex = new Regex("^((([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\\u" +
                "FDF0-\\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-\\uFF" +
                "EF])))\\.?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
        return _regex.IsMatch(email);
    }
    catch (RegexMatchTimeoutException)
    {
        return false;
    }
}

Also, You can use this:

http://msdn.microsoft.com/en-us/library/01escwtf(v=vs.110).aspx

Solution 28 - C#

I succinctified Poyson 1's answer like so:

public static bool IsValidEmailAddress(string candidateEmailAddr)
{
    string regexExpresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
    return (Regex.IsMatch(candidateEmailAddr, regexExpresion)) && 
           (Regex.Replace(candidateEmailAddr, regexExpresion, string.Empty).Length == 0);
}

Solution 29 - C#

Here is an answer to your question for you to check.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class RegexUtilities
{    
   public bool IsValidEmail(string strIn)
   {
       if (String.IsNullOrEmpty(strIn))
       {
          return false;

       }

       // Use IdnMapping class to convert Unicode domain names.

       try 
       {
          strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));

       }
       catch (RegexMatchTimeoutException) 
       {
           return false;

       }

       if (invalid)
       {
           return false;

       }

       // Return true if strIn is in valid e-mail format.    

       try 
       {
          return Regex.IsMatch(strIn, @"^(?("")("".+?(?<!\\)""@)|(([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));

       }
       catch (RegexMatchTimeoutException) 
       {
          return false;

       }

   }


   private string DomainMapper(Match match)
   {
      // IdnMapping class with default property values.

      IdnMapping idn = new IdnMapping();

      string domainName = match.Groups[2].Value;

      try 
      {
         domainName = idn.GetAscii(domainName);

      }
      catch (ArgumentException) 
      {
         invalid = true;

      }

      return match.Groups[1].Value + domainName;

   }

}

Solution 30 - C#

Simple way to identify the emailid is valid or not.

public static bool EmailIsValid(string email)
{
        return Regex.IsMatch(email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}

Solution 31 - C#

There is culture problem in regex in C# rather then js. So we need to use regex in US mode for email check. If you don't use ECMAScript mode, your language special characters are imply in A-Z with regex.

Regex.IsMatch(email, @"^([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.ECMAScript)

Solution 32 - C#

I ended up using this regex, as it successfully validates commas, comments, Unicode characters and IP(v4) domain addresses.

Valid addresses will be:

> " "@example.org > > (comment)[email protected] > > тест@example.org > > ტესტი@example.org > > test@[192.168.1.1]

 public const string REGEX_EMAIL = @"^(((\([\w!#$%&'*+\/=?^_`{|}~-]*\))?[^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))(\([\w!#$%&'*+\/=?^_`{|}~-]*\))?@((\[[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 33 - C#

A simple one without using Regex (which I don't like for its poor readability):

bool IsValidEmail(string email)
{
    string emailTrimed = email.Trim();

    if (!string.IsNullOrEmpty(emailTrimed))
    {
        bool hasWhitespace = emailTrimed.Contains(" ");

        int indexOfAtSign = emailTrimed.LastIndexOf('@');

        if (indexOfAtSign > 0 && !hasWhitespace)
        {
            string afterAtSign = emailTrimed.Substring(indexOfAtSign + 1);

            int indexOfDotAfterAtSign = afterAtSign.LastIndexOf('.');

            if (indexOfDotAfterAtSign > 0 && afterAtSign.Substring(indexOfDotAfterAtSign).Length > 1)
                return true;
        }
    }

    return false;
}

Examples:

It is meant to be simple and therefore it doesn't deal with rare cases like emails with bracketed domains that contain spaces (typically allowed), emails with IPv6 addresses, etc.

Solution 34 - C#

Based on the answer of @Cogwheel i want to share a modified solution that works for SSIS and the "Script Component":

  1. Place the "Script Component" into your Data Flow connect and then open it.

  2. In the section "Input Columns" set the field that contains the E-Mail Adresses to "ReadWrite" (in the example 'fieldName').

  3. Switch back to the section "Script" and click on "Edit Script". Then you need to wait after the code opens.

  4. Place this code in the right method:

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        string email = Row.fieldName;
    
        try
        {
            System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(email);
            Row.fieldName= addr.Address.ToString();
        }
        catch
        {
            Row.fieldName = "WRONGADDRESS";
        }
    }
    

Then you can use a Conditional Split to filter out all invalid records or whatever you want to do.

Solution 35 - C#

I came here to steal the verification code for the e-mail. Then I saw that the codes in the answers were unnecessarily extended. I believe I wrote the best solution in the shortest way:

public static bool IsEmail(string email)
{
    try
    {
        return new System.Net.Mail.MailAddress(email).Address == email && !email.Trim().EndsWith(".");
    }
    catch
    {
        return false;
    }
}

Solution 36 - C#

I wrote an function to check if an email is valid or not. It seems working well for me in most cases.

Results:

dasddas-@.com => FALSE
-asd@das.com => FALSE
as3d@dac.coas- => FALSE
dsq!a?@das.com => FALSE
_dasd@sd.com => FALSE
dad@sds => FALSE
asd-@asd.com => FALSE
dasd_-@jdas.com => FALSE
asd@dasd@asd.cm => FALSE
da23@das..com => FALSE
_dasd_das_@9.com => FALSE

d23d@da9.co9 => TRUE
dasd.dadas@dasd.com => TRUE
dda_das@das-dasd.com => TRUE
dasd-dasd@das.com.das => TRUE

Code:

    private bool IsValidEmail(string email)
    {
        bool valid = false;
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            valid = true;
        }
        catch
        {
            valid = false;
            goto End_Func;
        }

        valid = false;
        int pos_at = email.IndexOf('@');
        char checker = Convert.ToChar(email.Substring(pos_at + 1, 1));
        var chars = "qwertyuiopasdfghjklzxcvbnm0123456789";
        foreach (char chr in chars)
        {
            if (checker == chr)
            {
                valid = true;
                break;
            }
        }
        if (valid == false)
        {
            goto End_Func;
        } 

        int pos_dot = email.IndexOf('.', pos_at + 1);
        if(pos_dot == -1)
        {
            valid = false;
            goto End_Func;
        }

        valid = false;
        try
        {
            checker = Convert.ToChar(email.Substring(pos_dot + 1, 1));
            foreach (char chr in chars)
            {
                if (checker == chr)
                {
                    valid = true;
                    break;
                }
            }
        }
        catch
        {
            valid = false;
            goto End_Func;
        }

        Regex valid_checker = new Regex(@"^[[email protected]]*$");
        valid = valid_checker.IsMatch(email);
        if (valid == false)
        {
            goto End_Func;
        }

        List<int> pos_list = new List<int> { };
        int pos = 0;
        while (email.IndexOf('_', pos) != -1)
        {
            pos_list.Add(email.IndexOf('_', pos));
            pos = email.IndexOf('_', pos) + 1;
        }

        pos = 0;
        while (email.IndexOf('.', pos) != -1)
        {
            pos_list.Add(email.IndexOf('.', pos));
            pos = email.IndexOf('.', pos) + 1;
        }

        pos = 0;
        while (email.IndexOf('-', pos) != -1)
        {
            pos_list.Add(email.IndexOf('-', pos));
            pos = email.IndexOf('-', pos) + 1;
        }

        int sp_cnt = pos_list.Count();
        pos_list.Sort();
        for (int i = 0; i < sp_cnt - 1; i++)
        {
            if (pos_list[i] + 1 == pos_list[i + 1])
            {
                valid = false;
                break;
            }

            if (pos_list[i]+1 == pos_at || pos_list[i]+1 == pos_dot)
            {
                valid = false;
                break;
            }
        }
        
        if(valid == false)
        {
            goto End_Func;
        }

        if (pos_list[sp_cnt - 1] == email.Length - 1 || pos_list[0] == 0)
        {
            valid = false;
        }

    End_Func:;
        return valid;
    }

Solution 37 - C#

What if you combine multiple solutions to make a perfect code?

i got top 2 Solutions having highest Ranks and Reviews and combined them to get more accurate Answers. its Short, fast and adorable.

    public static bool isValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            if (addr.Address == email)
            {
                string expression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; 
                if (Regex.IsMatch(email, expression))
                {
                    if (Regex.Replace(email, expression, string.Empty).Length == 0) 
                        return true; 
                }
                return false;
            }
            return false; 
        }
        catch
        {
            return false;
        }  
    }

Solution 38 - C#

I use this one to validate emails often and it works like a charm. This validates that the email must have atleast one character before the @, and at least one character before the "."

public static bool ValidateEmail(string value, bool required, int minLength, int maxLength)
        {
           value = value.Trim();
           if (required == false && value == "") return true;
           if (required && value == "") return false;
           if (value.Length < minLength || value.Length > maxLength) return false;

           //Email must have at least one character before an @, and at least one character before the .
           int index = value.IndexOf('@');
           if (index < 1 || value.LastIndexOf('.') < index + 2) return false;
           return true;
        }

Solution 39 - C#

A shorter answer to your question is: Validating" an e-mail address with a reg-ex is something that any internet based service provider should desist from. The possibilities of kinds of domain names and e-mail addresses have increased so much in terms of variety, any attempt at validation, which is not well thought may end up denying some valid users into your system.

However, there is one good library available in C# i.e."Mailkit". Using this one can send a mail to the user inputted email ID and assess the response to take a call on admitting the email ID or not. The library supports the SMTPUTF8 flag, which enables the users to send emails to even the IDN based email addresses.

The longer answer is: There are three RFCs that lay down the foundation for the "Internet Message Format".

  1. RFC 822
  2. RFC 2822 (Supersedes RFC 822)
  3. RFC 5322 (Supersedes RFC 2822)

The RFC 5322, however, defines the e-mail IDs and their naming structure in the most technical manner. That is more suitable laying down the foundation an Internet Standard that liberal enough to allow all the use-cases yet, conservative enough to bind it in some formalism.

However, the e-mail validation requirement from the software developer community, has the following needs -

  • to stave off unwanted spammers
  • to ensure the user does not make inadvertent mistake
  • to ensure that the e-mail ID belongs to the actual person inputting it

They are not exactly interested in implementing a technically all-encompassing definition that allows all the forms (IP addresses, including port IDs and all) of e-mail id. The solution suitable for their use-case is expected to solely ensure that all the legitimate e-mail holders should be able to get through. The definition of "legitimate" differs vastly from technical stand-point (RFC 5322 way) to usability stand-point(this solution). The usability aspect of the validation aims to ensure that all the e-mail IDs validated by the validation mechanism belong to actual people, using them for their communication purposes. This, thus introduces another angle to the validation process, ensuring an actually "in-use" e-mail ID, a requirement for which RFC-5322 definition is clearly not sufficient.

Thus, on practical grounds, the actual requirements boil down to this -

  1. To ensure some very basic validation checks
  2. To ensure that the inputted e-mail is in use

Second requirement typically involves, sending a standard response seeking e-mail to the inputted e-mail ID and authenticating the user based on the action delineated in the response mechanism. This is the most widely used mechanism to ensure the second requirement of validating an "in use" e-mail ID. This does involve round-tripping from the back-end server implementation and is not a straight-forward single-screen implementation, however, one cannot do away with this.

The first requirement, stems from the need that the developers do not want totally "non e-mail like" strings to pass as an e-mail. This typically involves blanks, strings without "@" sign or without a domain name. Given the punycode representations of the domain names, if one needs to enable domain validation, they need to engage in full-fledged implementation that ensures a valid domain name. Thus, given the basic nature of requirement in this regard, validating for "@." is the only apt way of satisfying the requirement.

A typical regex that can satisfy this requirement is: ^[^@\s]+@[^@\s.]+.[^@\s.]+$ The above regex, follows the standard Perl regular-expression standard, widely followed by majority of the programming languages. The validation statement is: @.

For those who want to go one step deeper into the more relevant implementations, they can follow the following validation methodology. <e-mail local part>@<domain name>

For <e-mail local part> - Follow the guidelines by the "Universal Acceptance Steering Group" - UASG-026 - https://uasg.tech/download/uasg-028-considerations-for-naming-internationalized-email-mailboxes-en/ For <domain name>, you can follow any domain validation methodology using standard libraries, depending on your programming language. For the recent studies on the subject, follow the document UASG-018A - https://uasg.tech/download/uasg-018a-ua-compliance-of-some-programming-language-libraries-and-frameworks-en/. In addition, those who are interested to know the overall process, challenges and issues one may come across while implementing the Internationalized Email Solution, they can also go through the following RFCs: RFC 6530 (Overview and Framework for Internationalized Email), RFC 6531 (SMTP Extension for Internationalized Email), RFC 6532 (Internationalized Email Headers), RFC 6533 (Internationalized Delivery Status and Disposition Notifications), RFC 6855 (IMAP Support for UTF-8), RFC 6856 (Post Office Protocol Version 3 (POP3) Support for UTF-8), RFC 6857 (Post-Delivery Message Downgrading for Internationalized Email Messages), RFC 6858 (Simplified POP and IMAP Downgrading for Internationalized Email)."

Solution 40 - C#

  1. In a "try block" send a verification email.
  2. Make the user open the email and click a link verifying the email is real.

Until this process completes successfully, the email is assumed to be invalid.

Solution 41 - C#

Some time back, I wrote an EmailAddressValidationAttribute that should properly validate pretty much any relatively normal email address of the form

local-part@domain

It's a System.ComponentModel.DataAnnotations.ValidationAttribute, so usage is really simple.

And, since digging through all the RFCs and errata and assembling all the bits required to properly enumerate all the rules is...tedious — at best! — I posted the source code for the validator in my answer to the question https://stackoverflow.com/questions/6449367/c-sharp-email-address-validation for the source code.

My validator isn't perfect by any stretch of the imagination, though Just for starters, it doesn't have any built-in support for emitting client-side javascript validation, though it wouldn't be too difficult to add that in. From my answer above:

> Here's the validation attribute I wrote. It validates pretty much every "raw" email > address, that is those of the form local-part@domain. It doesn't support any of > the other, more...creative constructs that the RFCs allow (this list is not > comprehensive by any means): > > - comments (e.g., [email protected] (work)) > - quoted strings (escaped text, to allow characters not allowed in an atom) > - domain literals (e.g. foo@[123.45.67.012]) > - bang-paths (aka source routing) > - angle addresses (e.g. John Smith <[email protected]>) > - folding whitespace > - double-byte characters in either local-part or domain (7-bit ASCII only). > - etc. > > It should accept almost any email address that can be expressed thusly > > - [email protected] > > without requiring the use of quotes ("), angle brackets ('<>') > or square brackets ([]). > > No attempt is made to validate that the rightmost dns label in the domain is a valid > TLD (top-level domain). That is because the list of TLDs is far larger now than the > "big 6" (.com, .edu, .gov, .mil, .net, .org) plus 2-letter ISO country codes. > ICANN actually updates the TLD list daily, though I suspect that the list > doesn't actually change daily. Further, [ICANN just approved a big expansion of the > generic TLD namespace][2]). And some email addresses don't have what you'd recognize > as a TLD (did you know that postmaster@. is theoretically valid and mailable? Mail > to that address should get delivered to the postmaster of the DNS root zone.) > > Extending the regular expression to support domain literals shouldn't be too difficult.

Solution 42 - C#

I created an email address validation routine based on Wikipedia's documented rules and sample addresses. For those that don't mind looking at a little more code, here you go. Honestly, I had no idea how many crazy rules there were in the email address specification. I don't fully validate the hostname or ipaddress, but it still passes all of the test cases on wikipedia.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EmailValidateUnitTests
{
	[TestClass]
	public class EmailValidationUnitTests
	{
		[TestMethod]
		public void TestEmailValidate()
		{
			// Positive Assertions
			Assert.IsTrue("[email protected]".IsValidEmailAddress());
			Assert.IsTrue("[email protected]".IsValidEmailAddress());
			Assert.IsTrue("[email protected]".IsValidEmailAddress());
			Assert.IsTrue("[email protected]".IsValidEmailAddress());
			Assert.IsTrue("\"much.more unusual\"@example.com".IsValidEmailAddress());
			Assert.IsTrue("\"[email protected]\"@example.com".IsValidEmailAddress()); //"[email protected]"@example.com
			Assert.IsTrue("\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com".IsValidEmailAddress()); //"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
			Assert.IsTrue("admin@mailserver1".IsValidEmailAddress());
			Assert.IsTrue("#!$%&'*+-/=?^_`{}|[email protected]".IsValidEmailAddress());
			Assert.IsTrue("\"()<>[]:,;@\\\\\\\"!#$%&'*+-/=?^_`{}| ~.a\"@example.org".IsValidEmailAddress()); //"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org
			Assert.IsTrue("\" \"@example.org".IsValidEmailAddress()); //" "@example.org (space between the quotes)
			Assert.IsTrue("example@localhost".IsValidEmailAddress());
			Assert.IsTrue("[email protected]".IsValidEmailAddress());
			Assert.IsTrue("user@com".IsValidEmailAddress());
			Assert.IsTrue("user@localserver".IsValidEmailAddress());
			Assert.IsTrue("user@[IPv6:2001:db8::1]".IsValidEmailAddress());
			Assert.IsTrue("user@[192.168.2.1]".IsValidEmailAddress());
			Assert.IsTrue("(comment and stuff)[email protected]".IsValidEmailAddress());
			Assert.IsTrue("joe(comment and stuff)@gmail.com".IsValidEmailAddress());
			Assert.IsTrue("joe@(comment and stuff)gmail.com".IsValidEmailAddress());
			Assert.IsTrue("[email protected](comment and stuff)".IsValidEmailAddress());

			// Failure Assertions
			Assert.IsFalse("joe(fail me)[email protected]".IsValidEmailAddress());
			Assert.IsFalse("joesmith@gma(fail me)il.com".IsValidEmailAddress());
			Assert.IsFalse("[email protected](comment and stuff".IsValidEmailAddress());
			Assert.IsFalse("Abc.example.com".IsValidEmailAddress());
			Assert.IsFalse("A@b@[email protected]".IsValidEmailAddress());
			Assert.IsFalse("a\"b(c)d,e:f;g<h>i[j\\k][email protected]".IsValidEmailAddress()); //a"b(c)d,e:f;g<h>i[j\k][email protected]
			Assert.IsFalse("just\"not\"[email protected]".IsValidEmailAddress()); //just"not"[email protected]
			Assert.IsFalse("this is\"not\\[email protected]".IsValidEmailAddress()); //this is"not\[email protected]
			Assert.IsFalse("this\\ still\\\"not\\\\[email protected]".IsValidEmailAddress());//this\ still\"not\\[email protected]
			Assert.IsFalse("[email protected]".IsValidEmailAddress());
			Assert.IsFalse("[email protected]".IsValidEmailAddress());
			Assert.IsFalse(" [email protected]".IsValidEmailAddress());
			Assert.IsFalse("[email protected] ".IsValidEmailAddress());
		}
	}

	public static class ExtensionMethods
	{
		private const string ValidLocalPartChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+-/=?^_`{|}~";
		private const string ValidQuotedLocalPartChars = "(),:;<>@[]. ";
		private const string ValidDomainPartChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-:";

		private enum EmailParseMode
		{
			BeginLocal, Local, QuotedLocalEscape, QuotedLocal, QuotedLocalEnd, LocalSplit, LocalComment,
			At,
			Domain, DomainSplit, DomainComment, BracketedDomain, BracketedDomainEnd
		};

		public static bool IsValidEmailAddress(this string s)
		{
			bool valid = true;

			bool hasLocal = false, hasDomain = false;
			int commentStart = -1, commentEnd = -1;
			var mode = EmailParseMode.BeginLocal;
			for (int i = 0; i < s.Length; i++)
			{
				char c = s[i];
				if (mode == EmailParseMode.BeginLocal || mode == EmailParseMode.LocalSplit)
				{
					if (c == '(') { mode = EmailParseMode.LocalComment; commentStart = i; commentEnd = -1; }
					else if (c == '"') { mode = EmailParseMode.QuotedLocal; }
					else if (ValidLocalPartChars.IndexOf(c) >= 0) { mode = EmailParseMode.Local; hasLocal = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.LocalComment)
				{
					if (c == ')')
					{
						mode = EmailParseMode.Local; commentEnd = i;
						// comments can only be at beginning and end of parts...
						if (commentStart != 0 && ((commentEnd + 1) < s.Length) && s[commentEnd + 1] != '@') { valid = false; break; }
					}
				}
				else if (mode == EmailParseMode.Local)
				{
					if (c == '.') mode = EmailParseMode.LocalSplit;
					else if (c == '@') mode = EmailParseMode.At;
					else if (c == '(') { mode = EmailParseMode.LocalComment; commentStart = i; commentEnd = -1; }
					else if (ValidLocalPartChars.IndexOf(c) >= 0) { hasLocal = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.QuotedLocal)
				{
					if (c == '"') { mode = EmailParseMode.QuotedLocalEnd; }
					else if (c == '\\') { mode = EmailParseMode.QuotedLocalEscape; }
					else if (ValidLocalPartChars.IndexOf(c) >= 0 || ValidQuotedLocalPartChars.IndexOf(c) >= 0) { hasLocal = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.QuotedLocalEscape)
				{
					if (c == '"' || c == '\\') { mode = EmailParseMode.QuotedLocal; hasLocal = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.QuotedLocalEnd)
				{
					if (c == '.') { mode = EmailParseMode.LocalSplit; }
					else if (c == '@') mode = EmailParseMode.At;
					else if (c == '(') { mode = EmailParseMode.LocalComment; commentStart = i; commentEnd = -1; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.At)
				{
					if (c == '[') { mode = EmailParseMode.BracketedDomain; }
					else if (c == '(') { mode = EmailParseMode.DomainComment; commentStart = i; commentEnd = -1; }
					else if (ValidDomainPartChars.IndexOf(c) >= 0) { mode = EmailParseMode.Domain; hasDomain = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.DomainComment)
				{
					if (c == ')')
					{
						mode = EmailParseMode.Domain;
						commentEnd = i;
						// comments can only be at beginning and end of parts...
						if ((commentEnd + 1) != s.Length && (commentStart > 0) && s[commentStart - 1] != '@') { valid = false; break; }
					}
				}
				else if (mode == EmailParseMode.DomainSplit)
				{
					if (ValidDomainPartChars.IndexOf(c) >= 0) { mode = EmailParseMode.Domain; hasDomain = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.Domain)
				{
					if (c == '(') { mode = EmailParseMode.DomainComment; commentStart = i; commentEnd = -1; }
					else if (c == '.') { mode = EmailParseMode.DomainSplit; }
					else if (ValidDomainPartChars.IndexOf(c) >= 0) { hasDomain = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.BracketedDomain)
				{
					if (c == ']') { mode = EmailParseMode.BracketedDomainEnd; }
					else if (c == '.' || ValidDomainPartChars.IndexOf(c) >= 0) { hasDomain = true; }
					else { valid = false; break; }
				}
				else if (mode == EmailParseMode.BracketedDomain)
				{
					if (c == '(') { mode = EmailParseMode.DomainComment; commentStart = i; commentEnd = -1; }
					else { valid = false; break; }
				}
			}
			bool unfinishedComment = (commentEnd == -1 && commentStart >= 0);

			return hasLocal && hasDomain && valid && !unfinishedComment;
		}
	}
}

Solution 43 - C#

    /// <summary>
    /// Validates the email if it follows the valid email format
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns></returns>
    public static bool EmailIsValid(string emailAddress)
    {
        //if string is not null and empty then check for email follow the format
        return string.IsNullOrEmpty(emailAddress)?false : new Regex(@"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$", RegexOptions.IgnoreCase).IsMatch(emailAddress);
    }

Solution 44 - C#

This may be the best way for the email validation for your textbox.

string pattern = null;
pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";

if (Regex.IsMatch("txtemail.Text", pattern))
{
MessageBox.Show ("Valid Email address ");
}
else
{
MessageBox.Show("Invalid Email Email");
}

Just include in any function where you want.

Solution 45 - C#

public static bool IsEmail(string strEmail)
{
    Regex rgxEmail = 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})(\]?)$");
    return rgxEmail.IsMatch(strEmail);
}

Solution 46 - C#

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

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
QuestionleoraView Question on Stackoverflow
Solution 1 - C#CogwheelView Answer on Stackoverflow
Solution 2 - C#imjoshView Answer on Stackoverflow
Solution 3 - C#Manik AroraView Answer on Stackoverflow
Solution 4 - C#Chad GrantView Answer on Stackoverflow
Solution 5 - C#David Silva SmithView Answer on Stackoverflow
Solution 6 - C#KibbeeView Answer on Stackoverflow
Solution 7 - C#NaveenView Answer on Stackoverflow
Solution 8 - C#Poyson1View Answer on Stackoverflow
Solution 9 - C#WonderWorkerView Answer on Stackoverflow
Solution 10 - C#Noon SilkView Answer on Stackoverflow
Solution 11 - C#Matthew LockView Answer on Stackoverflow
Solution 12 - C#Mauricio SchefferView Answer on Stackoverflow
Solution 13 - C#Manuel FuchsView Answer on Stackoverflow
Solution 14 - C#Ralph NView Answer on Stackoverflow
Solution 15 - C#Corniel NobelView Answer on Stackoverflow
Solution 16 - C#Vasya MilovidovView Answer on Stackoverflow
Solution 17 - C#Joe CaffeineView Answer on Stackoverflow
Solution 18 - C#Efran CobisiView Answer on Stackoverflow
Solution 19 - C#user2211290View Answer on Stackoverflow
Solution 20 - C#Ulysses AlvesView Answer on Stackoverflow
Solution 21 - C#rethabileView Answer on Stackoverflow
Solution 22 - C#Phil CView Answer on Stackoverflow
Solution 23 - C#Liakat HossainView Answer on Stackoverflow
Solution 24 - C#FilipView Answer on Stackoverflow
Solution 25 - C#ErwanLentView Answer on Stackoverflow
Solution 26 - C#Rajib ChyView Answer on Stackoverflow
Solution 27 - C#Aina Ademola CView Answer on Stackoverflow
Solution 28 - C#B. Clay Shannon-B. Crow RavenView Answer on Stackoverflow
Solution 29 - C#Parsa KaramiView Answer on Stackoverflow
Solution 30 - C#Amit GorvadiyaView Answer on Stackoverflow
Solution 31 - C#mkysoftView Answer on Stackoverflow
Solution 32 - C#d.popovView Answer on Stackoverflow
Solution 33 - C#aBertrandView Answer on Stackoverflow
Solution 34 - C#user3772108View Answer on Stackoverflow
Solution 35 - C#Erçin DedeoğluView Answer on Stackoverflow
Solution 36 - C#Louis TranView Answer on Stackoverflow
Solution 37 - C#Sayed Muhammad IdreesView Answer on Stackoverflow
Solution 38 - C#Andrew ReeseView Answer on Stackoverflow
Solution 39 - C#ThinkTransView Answer on Stackoverflow
Solution 40 - C#Timothy ShieldsView Answer on Stackoverflow
Solution 41 - C#Nicholas CareyView Answer on Stackoverflow
Solution 42 - C#komma8.komma1View Answer on Stackoverflow
Solution 43 - C#farView Answer on Stackoverflow
Solution 44 - C#Iswor Lal ShresthaView Answer on Stackoverflow
Solution 45 - C#jesalView Answer on Stackoverflow
Solution 46 - C#Ronel GonzalesView Answer on Stackoverflow