mvc4 data annotation compare two dates

user2208349 picture user2208349 · Nov 9, 2013 · Viewed 56.4k times · Source

I have these two fields in my model:

[Required(ErrorMessage="The start date is required")]
[Display(Name="Start Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime startDate { get; set; }

[Required(ErrorMessage="The end date is required")]
[Display(Name="End Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime endDate{ get; set; }

I require that endDate must be greater than startDate. I tried using [Compare("startDate")] but this only works for the equal operation.

What should I use for the "greater than" operation?

Answer

Davor Zlotrg picture Davor Zlotrg · Nov 9, 2013

Take a look at Fluent Validation or MVC Foolproof Validation: those can help you a lot.

With Foolproof for example there is a [GreaterThan("StartDate")] annotation than you can use on your date property.

Or if you don't want to use other libraries, you can implement your own custom validation by implementing IValidatableObject on your model:

public class ViewModel: IValidatableObject
{
    [Required]
    public DateTime StartDate { get; set; }
    [Required]    
    public DateTime EndDate { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       if (EndDate < StartDate)
       {
           yield return new ValidationResult(
               errorMessage: "EndDate must be greater than StartDate",
               memberNames: new[] { "EndDate" }
          );
       }
    }
}