ASP.NET MVC3:如何验证电子邮件[compare] dataannotations是否具有不敏感性?

时间:2011-10-12 14:33:44

标签: 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 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 个答案:

答案 0 :(得分: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.")]