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


当前回答

在“尝试块”发送一个验证电子邮件。 让用户打开电子邮件并单击一个链接,以验证电子邮件是真实的。

在此过程成功完成之前,该电子邮件被认为是无效的。

其他回答

电子邮件地址验证并不像看起来那么简单。实际上,从理论上讲,仅使用正则表达式完全验证电子邮件地址是不可能的。

请查看我的博客文章,了解关于这个主题的讨论以及使用FParsec的f#实现。[/ shameless_plug]

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

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.

我从第1条中得到Phil的答案,并创建了这个类。 这样调用它:bool isValid = Validator.EmailIsValid(emailString);

下面是这个类:

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

在c#的regex中有文化问题,而不是js。所以我们需要在US模式下使用regex进行邮件检查。如果你不使用ECMAScript模式,你的语言特殊字符是在A-Z与正则表达式中隐含的。

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)