'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):
[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?
Thank you
Solution 1:[1]
You can add custom validation logic by implementing the IValidatableObject on your DTO class. Aside from adding the interface to your class definition, add the following method:
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.");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Glenn |
