如果有人仍然想知道如何比较两个日期并在验证 DataAnnotation 中使用它,您可以简单地添加一个扩展方法来比较开始日期和结束日期,如下所示。
假设这是您的课程:
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; }
}
}
您只需添加以下类作为验证器:
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;
}
}
}
}
然后您需要在 StartDate 上添加该 DataAnnotation,如下所示
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; }
}
}