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

前端 未结 4 723
我寻月下人不归
我寻月下人不归 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:58

    There is a way easier way to do this using set child validator:

    public class ChildValidator : AbstractValidator
    {
        public ChildValidator(Parent parent)
        {
            RuleFor(model => model.ChildProperty).NotEmpty();
            RuleFor(model => model.Birthday).Must(birthday => parent.Birthday > birthday);
    
        }
    }
    
    public class ParentValidator : AbstractValidator
    {
        public ParentValidator()
        {
             RuleFor(model => model.Name).NotEmpty();
        }
    
        public override ValidationResult Validate(Parent parent)
        {
            RuleFor(model => model.Children).SetCollectionValidator(new ChildValidator(this));
    
            return base.Validate();
        }
    
    }
    

提交回复
热议问题