2011-10-12 17 views
2

我想電子郵件與案件麻木不仁比較ASP.NET MVC3:如何驗證電子郵件[比較]數據註解與不敏感?

  [Display(Name = "E-mail *")] 
      //The regular expression below implements the official RFC 2822 standard for email addresses. Using this regular expression in actual applications is NOT recommended. It is shown to illustrate that with regular expressions there's always a trade-off between what's exact and what's practical. 
      [RegularExpression("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$", ErrorMessage = "Invalid e-mail.")] 

      [Required(ErrorMessage = "E-mail must be entered")] 
      [DataType(DataType.EmailAddress)] 
      public virtual string Email { get; set; } 

      [Display(Name = "Repeat e-mail *")] 
      [Required(ErrorMessage = "Repeat e-mail must be entered")] 
      [DataType(DataType.EmailAddress)] 
      [Compare("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")] 
      public virtual string Email2 { get; set; } 

任何人都知道該怎麼做?例如ToLower()比較。

回答

1

您將需要創建自己的屬性,從CompareAttribute繼承,並覆蓋IsValid方法,像這樣:然後

public class CompareStringCaseInsensitiveAttribute : CompareAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty); 
     if (otherPropertyInfo == null) 
      return new ValidationResult(String.Format(CultureInfo.CurrentCulture, MvcResources.CompareAttribute_UnknownProperty, OtherProperty)); 

     var otherPropertyStringValue = 
      otherPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString().ToLowerInvariant(); 
     if (!Equals(value.ToString().ToLowerInvariant(), otherPropertyStringValue)) 
      return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); 

     return null; 
    } 
} 

,改變[Compare("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")]到:

[CompareStringCaseInsensitive("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")]