Child Model Validation using Parent Model Values. Fluent Validation. MVC4

前端 未结 4 735
我寻月下人不归
我寻月下人不归 2020-12-25 11:13

Below is a simplified version of my problem.

I can not flatten the model. There is a List of \"children\" that I need to validate a birthday.

I can not seem

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-25 11:44

    Building on the answer of @kristoffer-jalen it is now:

    public class ParentValidator : AbstractValidator
    {
        public ParentValidator()
        {
             RuleFor(model => model.Name).NotEmpty();
             //RuleFor(model => model.Children)
             //    .SetCollectionValidator(model => new ChildValidator(model))
             RuleForEach(model => model.Children)
                    .SetValidator(model => new ChildValidator(model));
        }
    }
    
    public class ChildValidator : AbstractValidator
    {
        public ChildValidator(Parent parent)
        {
            RuleFor(model => model.ChildProperty).NotEmpty();
            RuleFor(model => model.Birthday).Must(birthday => parent.Birthday < birthday);
        }
    }
    

    as SetCollectionValidator is deprecated.

提交回复
热议问题