If anyone is still wondering how to compare two dates and use that in a validation DataAnnotation, you can simply add an extension method that will compare the start date and the end date like the following.
Assuming that this is your class:
using System;
using System.ComponentModel.DataAnnotations;
namespace Entities.Models
{
public class Periode
{
[Key]
public int PeriodeID { get; set; }
public string Name { get; set; }
[DataType(DataType.Date)]
[Display(Name ="Start Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
}
}
You simply add the following class as a validator:
namespace Entities.Models
{
public class StartEndDateValidator : ValidationAttribute
{
protected override ValidationResult
IsValid(object value, ValidationContext validationContext)
{
var model = (Models.Periode)validationContext.ObjectInstance;
DateTime EndDate = Convert.ToDateTime(model.EndDate);
DateTime StartDate = Convert.ToDateTime(value);
if (StartDate > EndDate)
{
return new ValidationResult
("The start date must be anterior to the end date");
}
else
{
return ValidationResult.Success;
}
}
}
}
And then you need to add that DataAnnotation on the StartDate as following
namespace Entities.Models
{
public class Periode
{
[Key]
public int PeriodeID { get; set; }
public string Name { get; set; }
[DataType(DataType.Date)]
[Display(Name ="Start Date")]
// You need to add the following line
[StartEndDateValidator]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
}
}