ModelState.IsValid 不验证集合属性并且总是 return true

ModelState.IsValid doesn't validate collection properties and always return true

我有这些类

    public class Shape
    {
        public Shape()
        {
            ShapeDetails = new List<ShapeDetail>();
        }

        public int ID { get; set; }
        public string Name { get; set; }
        public List<ShapeDetail> ShapeDetails { get; set; }
    }

    public class ShapeValidator : AbstractValidator<Shape>
    {
        public ShapeValidator()
        {
            RuleFor(x => x.Name).NotEmpty().Length(1, 225);
        }
    }

public class ShapeDetail
{
    public int ID { get; set; }
    public decimal RangeFrom { get; set; }
    public decimal RangeTo { get; set; }
    public decimal Price { get; set; }
    public int ShapeID { get; set; }
    [NonPersistent]
    public Shape Shape { get; set; }
}

public class ShapeDetailValidator : AbstractValidator<ShapeDetail>
{
    public ShapeDetailValidator()
    {
        RuleFor(x => x.RangeFrom).NotEmpty().LessThan(100);
        RuleFor(x => x.RangeTo).NotEmpty().LessThan(100);
        RuleFor(x => x.Price).NotEmpty().LessThan(9999999999);
    }
}

当我在 Shape 上调用 ModelState.IsValid 时,它始终 return 为真,似乎它没有验证 ShapeDetail,我如何包含 ShapeDetails 在验证中?

谢谢

找到答案,需要在ShapeValidator

中添加RuleForEach
public class ShapeValidator : AbstractValidator<Shape>
{
    public ShapeValidator()
    {
        RuleFor(x => x.Name).NotEmpty().Length(1, 225);
        RuleForEach(x => x.ShapeDetails).SetValidator(new ShapeDetailValidator());
    }
}

来源:https://fluentvalidation.net/start#collections