+1  A: 

.NET regular expression syntax is not the same as in PHP, and Regex is the only built-in class to use regular expression (but there might be other third party implementation). Anyway, it's pretty easy to validate an email address with Regex... straight from the source

^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$
Thomas Levesque
This fails several of the tests on this site: http://fightingforalostcause.net/misc/2006/compare-email-regex.php
DanM
+2  A: 

The problem with your regular expression in .NET is that the possessive quantifiers aren't supported. If you remove those, it works. Here's the regular expression as a C# string:

@"^[-_a-z0-9\'+*$^&%=~!?{}]+(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d+)?$"

Here's a test bed for it based on the page you linked to, including all the strings that should match and the first three of those that shouldn't:

using System;
using System.Text.RegularExpressions;

public class Program
{
    static void Main(string[] args)
    {
        foreach (string email in new string[]{
            "[email protected]",
            "[email protected]",
            "hasApostrophe.o'[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]:25",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "&*=?^+{}'[email protected]",
            "[email protected]",
            "@missingLocal.org",
            "missingatSign.net"
        })
        {
            string s = @"^[-_a-z0-9\'+*$^&%=~!?{}]+(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d+)?$";
            bool isMatch = Regex.IsMatch(email, s, RegexOptions.IgnoreCase);
            Console.WriteLine(isMatch);
        }
    }
}

Output:

True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
False
False
False

A problem though is that it fails to match some valid email-addresses, such as foo\@[email protected]. It's better too match too much than too little.

Mark Byers
Thanks for your attempt, but this rejects all but two of the valid emails on this site: http://fightingforalostcause.net/misc/2006/compare-email-regex.php, so the conversion is not equivalent.
DanM
Did you remember to use case insensitive matching? Only two of those emails have only lower case, and I'm guessing those were the two you matched successfully. I've added some code to show how the regular expression should be used with the IgnoreCase option.
Mark Byers
With `RegexOptions.IgnoreCase`, it only accepts [email protected] and [email protected]. All the other valid emails are rejected.
DanM
I've checked it myself. It works for all the emails given! You must have an error in your code. I'll provide more source code.
Mark Byers
@Mark, my apologies. Just checked my code this morning, and I had put the `IgnoreCase` in one part of my code but not the other. After fixing this, the results look *much* better. It accepts all the valid emails, and the only invalid ones it accepts are [email protected] and local@SecondLevelDomainNamesAreInvalidIfTheyAreLongerThan64Charactersss.org.
DanM
A: 

I've used this function before in a bunch of e-commerce applications and never had a problem.

    public static bool IsEmailValid(string emailAddress)
    {
        Regex emailRegEx = new Regex(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b");
        if (emailRegEx.IsMatch(emailAddress))
        {
            return true;
        }

        return false;
    }
Jason Too Cool Webs
+2  A: 

You really shouldn't be using a RegEx to parse email addresses in .NET. Your better option is to use the functionality built into the framework.

Try to use your email string in the constructor of the MailAddress class. If it throws a FormatException then the address is no good.

try 
{
    MailAddress addr = new MailAddress("[email protected]")
    // <- Valid email if this line is reached
}
catch (FormatException)
{
    // <- Invalid email if this line is reached
}

You can see an answer a Microsoft developer gave to another email validation question, where he explains how .NET's email parsing has also improved dramatically in .NET 4.0. Since at the time of answering this, .NET 4.0 is still in beta, you probably aren't running it, however even previous versions of the framework have adequate email address parsing code. Remember, in the end you're most likely going to be using the MailAddress class to send your email anyway. Why not use it to validation your email addresses. In the end, being valid to the MailAddress class is all that matters anyway.

Dan Herbert
Testing on .NET 3.5, it accepts quite a few invalid email addresses: [email protected], missingDot@com, [email protected], [email protected], [email protected], [email protected], [email protected], and local@SecondLevelDomainNamesAreInvalidIfTheyAreLongerThan64Charactersss.org. That said, you make a good point about using `MailAddress` to send the emails anyway. And maybe .NET 4.0 does a better job.
DanM
@DanThMan Those addresses aren't necessarily invalid. Most of those addresses you mentioned are possible on internal networks, and therefore can potentially be valid. Remember, it's better to allow invalid addresses than reject valid ones.
Dan Herbert
@Dan, another good point, but for this particular application, I'm definitely expecting internet email addresses (rather than intranet). At the moment, though, I think I like this solution the best. I will actually need to send out emails, so using `MainAddress` to validate seems like the way to go.
DanM