Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 30th, 2012  |  syntax: None  |  size: 2.03 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. ASP.NET MVC3: How to validate e-mail [compare] dataannotations with insensitivity?
  2. [Display(Name = "E-mail *")]
  3.             //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.
  4.             [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.")]
  5.  
  6.             [Required(ErrorMessage = "E-mail must be entered")]
  7.             [DataType(DataType.EmailAddress)]
  8.             public virtual string Email { get; set; }
  9.  
  10.             [Display(Name = "Repeat e-mail *")]
  11.             [Required(ErrorMessage = "Repeat e-mail must be entered")]
  12.             [DataType(DataType.EmailAddress)]
  13.             [Compare("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")]
  14.             public virtual string Email2 { get; set; }
  15.        
  16. public class CompareStringCaseInsensitiveAttribute : CompareAttribute
  17. {
  18.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  19.     {
  20.         PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
  21.         if (otherPropertyInfo == null)
  22.             return new ValidationResult(String.Format(CultureInfo.CurrentCulture, MvcResources.CompareAttribute_UnknownProperty, OtherProperty));
  23.  
  24.         var otherPropertyStringValue =
  25.            otherPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString().ToLowerInvariant();
  26.         if (!Equals(value.ToString().ToLowerInvariant(), otherPropertyStringValue))
  27.             return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
  28.  
  29.         return null;
  30.     }
  31. }
  32.        
  33. [CompareStringCaseInsensitive("Email", ErrorMessage = "E-mail and Repeat e-mail must be identically entered.")]