ModelState.IsValid不验证集合属性,并且始终返回true

时间:2019-06-08 18:27:56

标签: c# asp.net-mvc .net-core fluentvalidation

我有这些课程

    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);
    }
}

当我在ModelState.IsValid上调用Shape时,它始终返回true,似乎没有验证ShapeDetail,如何在验证中包括ShapeDetails? / p>

谢谢

1 个答案:

答案 0 :(得分:1)

找到答案,需要在RuleForEach中添加ShapeValidator

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