Advertisement
Venciity

DateGreaterThanAttribute

Jul 22nd, 2016
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Web;
  6.  
  7. [AttributeUsage(AttributeTargets.Property)]
  8. public class DateGreaterThanAttribute : ValidationAttribute
  9. {
  10.     public DateGreaterThanAttribute(string dateToCompareToFieldName)
  11.     {
  12.         DateToCompareToFieldName = dateToCompareToFieldName;
  13.     }
  14.  
  15.     public string DateToCompareToFieldName { get; private set; }
  16.  
  17.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  18.     {
  19.         if (value == null)
  20.         {
  21.             return ValidationResult.Success;
  22.         }
  23.  
  24.         var laterDate = (DateTime?)value;
  25.         var earlierDate = (DateTime?)validationContext
  26.             .ObjectType
  27.             .GetProperty(DateToCompareToFieldName)
  28.             .GetValue(validationContext.ObjectInstance);
  29.  
  30.         if (laterDate > earlierDate)
  31.         {
  32.             return ValidationResult.Success;
  33.         }
  34.  
  35.         return new ValidationResult("Date is not later than other.");
  36.     }
  37.  
  38.     public override string FormatErrorMessage(string name)
  39.     {
  40.         return string.Format("{0} must be greather than {1}", name, this.DateToCompareToFieldName);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement