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

2 Answers 2

2

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.");
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.