2012-09-21 27 views
2

我對SO有read有關驗證與MailAddress電子郵件,併產生了如下因素代碼:Validaiting電子郵件與Net.Mail MailAddress

try 
        { 
         var address = new MailAddress(value.Email); 
        } 
        catch (FormatException) 
        { 
         emailError = "Invalid Email"; 

} 

令我大爲吃驚的字符串[email protected]驗證作爲良好的電子郵件。 任何想法爲什麼這樣?

+3

這可能不是有效的WWW域名,但在專用網絡上,我認爲這是一個有效的域名。如果你想得到更多的選擇,然後正則表達式。 – Paparazzi

+1

請注意:不要在驗證電子郵件地址時過度使用。相信我,這比它的價值更麻煩。 – Arran

+0

如果你要留下來,我作爲答案張貼。 – Paparazzi

回答

1

如果你真的需要過濾的電子郵件地址,你可以使用這個小工具找到here,它使用正則表達式驗證電子郵件地址。請注意,這是.Net 4.0版本 - 它與4.5有點不同。

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

public class RegexUtilities 
{ 
    bool invalid = false; 

    public bool IsValidEmail(string strIn) 
    { 
     invalid = false; 
     if (String.IsNullOrEmpty(strIn)) 
      return false; 

     // Use IdnMapping class to convert Unicode domain names. 
     strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper); 
     if (invalid) 
      return false; 

     // Return true if strIn is in valid e-mail format. 
     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]{2,17}))$", 
       RegexOptions.IgnoreCase); 
    } 

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

否則,如果它是用戶註冊,我通常只是依靠電子郵件驗證 - 即,系統向用戶發送一封電子郵件,鏈接,因此點擊鏈接驗證該電子郵件地址是真實的。

有可能有效電子郵件地址不是真實之一。換句話說,它甚至可以通過一個完美的驗證系統,但這並不能保證它存在。

1

這可能不是有效的WWW域名,但在私人網絡上,我認爲這是一個有效的域名。如果你想得到更多的選擇,然後正則表達式。

我試着解析合法使用正則表達式的電子郵件(消除垃圾郵件所使用的假冒),它很混亂。

如果你有機會到實際的電子郵件標題,然後它並沒有真正變得更容易,但它得到更準確。