Reputation: 99
I would like to compare e-mails with case insensitivity
[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; }
Anybody know how to do that? For example with ToLower() comparison.
Upvotes: 2
Views: 4336
Reputation: 10924
You will need to create your own attribute, inheriting from CompareAttribute
, and override the IsValid
method, like so:
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;
}
}
Then, change [Compare("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")]
to:
[CompareStringCaseInsensitive("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")]
Upvotes: 1