0

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

midowu
  • 697
  • 1
  • 10
  • 23

2 Answers2

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.");
}
John Glenn
  • 1,249
  • 7
  • 13
0

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

Sascha
  • 10,000
  • 3
  • 42
  • 63