验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?


当前回答

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);
}

其他回答

这是一个老问题,但我在SO上找到的所有答案,包括最近的答案,都与这个问题类似。然而,在。net 4.5 / MVC 4中,你可以通过从System.ComponentModel中添加[EmailAddress]注释来向表单添加电子邮件地址验证。DataAnnotations,所以我想知道为什么我不能只使用。net的内置功能。

这似乎是可行的,而且在我看来是相当优雅的:

using System.ComponentModel.DataAnnotations;

class ValidateSomeEmails
{
    static void Main(string[] args)
    {
        var email = new EmailAddressAttribute();
        email.IsValid("someone@somewhere.com");         //true
        email.IsValid("someone@somewhere.co.uk");       //true
        email.IsValid("someone+tag@somewhere.net");     //true
        email.IsValid("futureTLD@somewhere.fooo");      //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("someone@somewhere.com")) 
            return true;
    }
}

另一个正则表达式匹配答案:

   /// <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;
    }

我写了一个函数来检查电子邮件是否有效。在大多数情况下,这似乎对我很有效。

结果:

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

代码:

    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(@"^[a-zA-Z0-9_@.-]*$");
        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;
    }

以前,我写了一个EmailAddressValidationAttribute,它应该正确地验证表单中几乎任何相对正常的电子邮件地址

local-part@domain

它是System.ComponentModel.DataAnnotations。ValidationAttribute,所以使用非常简单。

而且,由于挖掘所有rfc和勘误表,并组装所需的所有位来正确枚举所有规则……太乏味了!-我在回答c#电子邮件地址验证源代码的问题时发布了验证器的源代码。

我的验证器无论怎么想象都不是完美的,只是对于初学者来说,它没有任何内置的对发出客户端javascript验证的支持,尽管将其添加进来并不太难。从我上面的回答来看:

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., jsmith@whizbang.com (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 <jsmith@whizbang.com>) 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 foo.bar@bazbat.com 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.

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);
}