C# attribute to check whether one date is earlier than the other

asp.net, asp.net-mvc-4, c#

Solution

Here is a very quick basic implementation (without error checking etc.) that should do what you ask (only on server side...it will not do asp.net client side javascript validation). I haven't tested it, but should be enough to get you started.

using System;
using System.ComponentModel.DataAnnotations;

namespace Test
{
   [AttributeUsage(AttributeTargets.Property)]
   public class DateGreaterThanAttribute : ValidationAttribute
   {
      public DateGreaterThanAttribute(string dateToCompareToFieldName)
      {
          DateToCompareToFieldName = dateToCompareToFieldName;
      }

       private string DateToCompareToFieldName { get; set; }

       protected override ValidationResult IsValid(object value, ValidationContext validationContext)
       {
           DateTime earlierDate = (DateTime)value;

           DateTime laterDate = (DateTime)validationContext.ObjectType.GetProperty(DateToCompareToFieldName).GetValue(validationContext.ObjectInstance, null);

           if (laterDate > earlierDate)
           {
               return ValidationResult.Success;
           }
           else
           {
               return new ValidationResult("Date is not later");
           }
       }
   }


   public class TestClass
   {
       [DateGreaterThan("ReturnDate")]
       public DateTime RentDate { get; set; }

       public DateTime ReturnDate { get; set; }
   }
}

Problem

I have a ViewModel for my MVC4 Prject containing two DateTime properties: ``` [Required] [DataType(DataType.Date)] public DateTime RentDate { get; set; } [Required] [DataType(DataType.Date)] public DateTime ReturnDate { get; set; } ``` Is there a simple way to use C# attributes as `[Compare("someProperty")]` to check weather the value of RentDate property is earlier than the value of ReturnDate?

Original source

Related problems