[英]ASP.NET Core Web API - How to validate EndDate greater than StartDate in EF
In my ASP.NET Core Web API Entity Framework Data Annotaion Code first, I have this code in DTO (Data Transformation Object):在我的 ASP.NET Core Web API 实体框架数据注释代码中,我在 DTO(数据转换对象)中有此代码:
[DataType(DataType.Date)]
[Display(Name = "Start Date")]
[Required(ErrorMessage = "Start Date is Required")]
[JsonProperty(PropertyName = "StartDate")]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "End Date")]
[Required(ErrorMessage = "End Date is Required")]
[JsonProperty(PropertyName = "EndDate")]
public DateTime EndDate { get; set; }
How do I validate that EndDate must be greater than StartDate?如何验证 EndDate 必须大于 StartDate?
Thank you谢谢
Instead of auto-implemented properties you could use an instance variable and use the setter to check for yourself.您可以使用实例变量并使用 setter 自行检查,而不是自动实现的属性。
Also you could get some inspiration from Conditionally required property using data annotations您还可以使用数据注释从条件需要的属性中获得一些灵感
You can add custom validation logic by implementing the IValidatableObject
on your DTO class.您可以通过在 DTO class 上实现IValidatableObject
来添加自定义验证逻辑。 Aside from adding the interface to your class definition, add the following method:除了将接口添加到 class 定义之外,还添加以下方法:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// if either date is null, that date's required attribute will invalidate
if (StartDate != null && EndDate != null && StartDate >= EndDate)
yield return new ValidationResult("EndDate is not greater than StartDate.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.