I have implemented custom model validator using dataanotations, where I wanted to compare two dates and validate if one is greater than other or not. It works fine in POST(create) endpoint.
However the problem is in PUT(update) endpoint.
Because in PUT method, we want to get one date from database using the {id} which is in PUT endpoint.
public class Contract
{
[JsonPropertyName("StartDate")]
public DateTime StartDate { get; set; }
[DateGreaterThan("StartDate", ErrorMessage="EndDate must be greate than start date.")]
[JsonPropertyName("EndDate")]
public DateTime EndDate { get; set; }
}
internal class DateGreaterThanAttribute : ValidationAttribute
{
private readonly string _comparisonProperty;
public DateGreaterThanAttribute(string comparisonProperty)
{
_comparisonProperty = comparisonProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get your StartDate and EndDate from model and value
DateTime StartDate = (DateTime)value;
var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
if (property == null)
{
throw new ArgumentException("Comparison property with this name not found");
}
var comparisonValue = property.GetValue(validationContext.ObjectInstance);
// perform comparison
//This works in POST
if (StartDate < (DateTime)comparisonValue)
{
return new ValidationResult("start date must be less than the end date");
}
else
{
return ValidationResult.Success;
}
//Now in case of PUT, I want to get StartDate from database quering the record using "id"(1234 in below example) from Route of endpoint
//httpd:localhost:5001//mycontroller/1234
}
}
I have tried many solutions but none of them is close to this.
We can not do this validation in Controller as per the requirement from business.
It has to be model base validation.