Validator.TryValidateObject does not call Remote validation

試著忘記壹切 提交于 2019-12-07 18:28:17

问题


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?

来源:https://stackoverflow.com/questions/43426916/validator-tryvalidateobject-does-not-call-remote-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!