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

前端 未结 6 1689
孤独总比滥情好
孤独总比滥情好 2021-02-07 15:05

I have a ViewModel for my MVC4 Prject containing two DateTime properties:

[Required]
[DataType(DataType.Date)]
public DateTime RentDate { get; set; }

[Required]         


        
6条回答
  •  名媛妹妹
    2021-02-07 15:32

    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; }
       }
    }
    

提交回复
热议问题