簡體   English   中英

C#電子郵件地址驗證

[英]C# Email Address validation

我想澄清一件事。 根據客戶端請求,我們必須創建一個正則表達式,以便它允許在電子郵件地址中使用撇號。

我的問題根據RFC標准,電子郵件地址是否包含aportrophe? 如果是這樣,如何重新創建正則表達式以允許撇號

下面的正則表達式實現了電子郵件地址的官方RFC 2822標准。 不建議在實際應用程序中使用此正則表達式。 它表明,使用正則表達式總是在精確和實際之間進行權衡。

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

您可以使用簡化的:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

是的,只要撇號不在域名中,就允許在電子郵件中使用撇號。

這是我寫的驗證屬性。 它幾乎驗證了每個“原始”電子郵件地址,即local-part @ * domain *形式的電子郵件地址。 它不支持RFC允許的任何其他更多......創造性結構(此列表無論如何都不全面):

  • 評論(例如, jsmith@whizbang.com (work)
  • 引用的字符串(轉義文本,允許原子中不允許的字符)
  • 域文字(例如foo@[123.45.67.012]
  • bang-paths(又名源路由)
  • 角度地址(例如John Smith <jsmith@whizbang.com>
  • 折疊空白
  • 本地部分域中的雙字節字符(僅限7位ASCII)。
  • 等等

它應該接受幾乎任何可以表達的電子郵件地址

  • foo.bar@bazbat.com

無需使用引號( " ),尖括號('<>')或方括號( [] )。

沒有嘗試驗證域中最右邊的DNS標簽是否是有效的TLD(頂級域)。 這是因為TLD列表現在比“大6”(.com,.edu,.gov,.mil,.net,.org)加上2個字母的ISO國家/地區代碼要大得多。 ICANN實際上每天更新TLD列表 ,但我懷疑該列表實際上並未每天更改。 此外, ICANN剛剛批准了通用TLD命名空間的大規模擴展 有些電子郵件地址沒有你認可的TLD(你知道postmaster@.理論上是有效且可郵寄的嗎?到該地址的郵件應該交付給DNS根區域的郵局主管。)

擴展正則表達式以支持域文字,這應該不會太困難。

干得好。 使用它健康:

using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace ValidationHelpers
{
  [AttributeUsage( AttributeTargets.Property | AttributeTargets.Field , AllowMultiple = false )]
  sealed public class EmailAddressValidationAttribute : ValidationAttribute
  {
    static EmailAddressValidationAttribute()
    {
      RxEmailAddress = CreateEmailAddressRegex();
      return;
    }

    private static Regex CreateEmailAddressRegex()
    {
      // references: RFC 5321, RFC 5322, RFC 1035, plus errata.
      string atom             = @"([A-Z0-9!#$%&'*+\-/=?^_`{|}~]+)"                 ;
      string dot              = @"(\.)"                                            ;
      string dotAtom          =  "(" + atom + "(" + dot + atom + ")*" + ")"        ;
      string dnsLabel         = "([A-Z]([A-Z0-9-]{0,61}[A-Z0-9])?)"                ;
      string fqdn             = "(" + dnsLabel + "(" + dot + dnsLabel + ")*" + ")" ;

      string localPart        = "(?<localpart>" + dotAtom + ")"      ;
      string domain           = "(?<domain>" + fqdn + ")"            ;
      string emailAddrPattern = "^" + localPart + "@" + domain + "$" ;

      Regex instance = new Regex( emailAddrPattern , RegexOptions.Singleline | RegexOptions.IgnoreCase );
      return instance;
    }

    private static Regex RxEmailAddress;

    public override bool IsValid( object value )
    {
      string s      = Convert.ToString( value ) ;
      bool   fValid = string.IsNullOrEmpty( s ) ;

      // we'll take an empty field as valid and leave it to the [Required] attribute to enforce that it's been supplied.
      if ( !fValid )
      {
        Match m = RxEmailAddress.Match( s ) ;

        if ( m.Success )
        {
          string emailAddr              = m.Value ;
          string localPart              = m.Groups[ "localpart" ].Value ;
          string domain                 = m.Groups[ "domain"    ].Value ;
          bool   fLocalPartLengthValid  = localPart.Length >= 1 && localPart.Length <=  64 ;
          bool   fDomainLengthValid     = domain.Length    >= 1 && domain.Length    <= 255 ;
          bool   fEmailAddrLengthValid  = emailAddr.Length >= 1 && emailAddr.Length <= 256 ; // might be 254 in practice -- the RFCs are a little fuzzy here.

          fValid = fLocalPartLengthValid && fDomainLengthValid && fEmailAddrLengthValid ;

        }
      }

      return fValid ;
    }

  }
}

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM