Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 533
cLar Avatar asked Dec 07 '12 14:12

cLar


1 Answers

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

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.RentDate > this.ReturnDate)
    {
        yield return new ValidationResult("Rent date must be prior to return date", new[] { "RentDate" });
    }
}
like image 155
Trevor Pilley Avatar answered Oct 07 '22 10:10

Trevor Pilley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!