【问题标题】:ModelState.IsValid doesn't validate collection properties and always return trueModelState.IsValid 不验证集合属性并始终返回 true
【发布时间】:2019-10-23 20:02:00
【问题描述】:

我有这些课程

    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 时,它总是返回true,似乎它没有验证ShapeDetail,如何在验证中包含ShapeDetails

谢谢

【问题讨论】:

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


    【解决方案1】:

    找到答案了,需要在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

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多