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

前端 未结 6 1768
孤独总比滥情好
孤独总比滥情好 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:37

    It looks like you're using DataAnnotations so another alternative is to implement IValidatableObject in the view model:

    public IEnumerable Validate(ValidationContext validationContext)
    {
        if (this.RentDate > this.ReturnDate)
        {
            yield return new ValidationResult("Rent date must be prior to return date", new[] { "RentDate" });
        }
    }
    

提交回复
热议问题