ASP.NET MVC3: как проверять электронную почту [сравнивать] аннотации данных с нечувствительностью? - PullRequest
2 голосов
/ 12 октября 2011

Я хотел бы сравнить электронную почту с регистром нечувствительность

            [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 Ответ

1 голос
/ 12 октября 2011

Вам нужно будет создать свой собственный атрибут, унаследованный от 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.")]
...