I have a class with a remote validation data annotation as follows:
public partial class LuInspectionWindow
{
[Required]
public int InspectionWindowId { get; set; }
[Required]
public string Description { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[Remote("ValidateWindowEndDate", "InspectionWindow", AdditionalFields = "StartDate")]
public DateTime EndDate { get; set; }
}
That calls this annotation:
[AcceptVerbs("Get", "Post")]
public IActionResult ValidateWindowEndDate(DateTime? endDate, DateTime? startDate)
{
int minWeeks = 8;
if (startDate.HasValue && endDate.HasValue
&& (endDate < startDate.Value.AddDays(minWeeks * 7)))
{
return Json(data: $"Inspection window end date must be at least {minWeeks} weeks after start date.");
}
return Json(data: true);
}
If I invalidate the object and then validate it as follows I only get one error, for the null Description (which is marked Required
), the remote validation is not checked at all.
luInspectionWindow.EndDate = luInspectionWindow.StartDate.AddDays(1);
luInspectionWindow.Description = null;
var context = new ValidationContext(
luInspectionWindow, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(luInspectionWindow, context, results);
await _context.SaveChangesAsync();
The remote validation works fine from the view, so it is wired up correctly. Is Validator.TryValidateObject
expected to check remote validations?