
Untitled
By: a guest on
May 30th, 2012 | syntax:
None | size: 2.03 KB | hits: 19 | expires: Never
ASP.NET MVC3: How to validate e-mail [compare] dataannotations with 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; }
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;
}
}
[CompareStringCaseInsensitive("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")]