首先在我的 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?
謝謝
uj5u.com熱心網友回復:
您可以使用實體變數并使用 setter 自行檢查,而不是自動實作的屬性。
您還可以使用資料注釋從條件需要的屬性中獲得一些靈感
uj5u.com熱心網友回復:
您可以通過IValidatableObject在 DTO 類上實作來添加自定義驗證邏輯。除了將介面添加到類定義之外,還添加以下方法:
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.");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420768.html
標籤:
