我有一个带有远程验证数据注释的类,如下所示:
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; }
}
调用此注释:
[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);
}
如果我使对象无效,然后按如下方式验证它,我只得到一个错误,对于空描述(标记为Required
),根本不检查远程验证。
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();
远程验证在视图中工作正常,因此它已正确连接。期望Validator.TryValidateObject
检查远程验证吗?