Home > other >  ASP.NET Core Web API - How to validate EndDate greater than StartDate in EF
ASP.NET Core Web API - How to validate EndDate greater than StartDate in EF

Time:01-25

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

CodePudding user response:

Instead of auto-implemented properties you could use an instance variable and use the setter to check for yourself.

Also you could get some inspiration from Conditionally required property using data annotations

CodePudding user response:

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.");
}
  •  Tags:  
  • Related