Asp.net mvc 3 ASP.NET MVC3:如何在不敏感的情况下验证电子邮件[比较]数据批注?

Asp.net mvc 3 ASP.NET MVC3:如何在不敏感的情况下验证电子邮件[比较]数据批注?,asp.net-mvc-3,data-annotations,Asp.net Mvc 3,Data Annotations,我想将电子邮件与不敏感的案例进行比较 [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

我想将电子邮件与不敏感的案例进行比较

            [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()比较。

您需要创建自己的属性,继承自
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;
    }
}
然后,将
[比较(“电子邮件”,ErrorMessage=“电子邮件和重复电子邮件必须相同地输入。”)]
更改为:

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