[英]ASP.NET Core Web API - How to validate EndDate greater than StartDate in EF
在我的 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; }
如何驗證 EndDate 必須大於 StartDate?
謝謝
您可以使用實例變量並使用 setter 自行檢查,而不是自動實現的屬性。
您還可以使用數據注釋從條件需要的屬性中獲得一些靈感
您可以通過在 DTO class 上實現IValidatableObject
來添加自定義驗證邏輯。 除了將接口添加到 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.