Fluentvalidation – 将参数传递给集合validation器

我在ASP.NET MVC应用程序中使用流畅的validation,我遇到了问题。 这是我的规则:

RuleFor(x => x.SimpleList) .SetCollectionValidator(new SimpleListValidator()) .When(x => x.Type == SimpleEnum.SpecificType); 

我想将x.Type param传递给SimpleListValidator,我该怎么做? 某种延伸方法? 它应该看起来像:

  RuleFor(x => x.SimpleList) .SetCollectionValidator(new SimpleListValidator(x => x.Type)) .When(x => x.Type == SimpleEnum.SpecificType); 

为属性设置集合validation器后 – 您可以忘记事实,主模型和(n - 1)子模型存在,除了当前validation的子模型。 并且无法将主模型作为参数传递给SetCollectionValidator

所以你必须使用RuleForEach方法而不是设置集合validation器:

 RuleForEach(x => x.SubEntities) .Must((model, submodel) => IsValidFirst(submodel, model)) // your rules should go here to be applicable to each collection item .WithMessage("The item with values {0}, {1} has duplicates in collection of {2} items", (model, submodel) => submodel.Field1, (model, submodel) => submodel.Field2, (model, submodel) => model.SubEntities.Count); // for error message building you can access both model and submodel being validated .Must((model, submodel) => IsValidSecond(submodel, model)) // yet another rule .WithMessage("...") .When(model => model.Type == SimpleEnum.SpecificType) // can access to main model only, but it is enough for your purposes 

我想有可能告诉儿童validation员关于事实,父模型可能存在,应该在将来实施,但现在有唯一的工作方法,如上所述。

UPDATE

您可以创建自定义ModelBinder ,将每个子实体的Parent属性设置为主实体值,并继续使用SetCollectionValidator()

这是可能的,你可以这样做:

 RuleFor(x => x.SimpleList) .SetCollectionValidator(model => new SimpleListValidator(model)) .When(x => x.Type == SimpleEnum.SpecificType); 

在您的SetCollectionValidator类中,您必须创建一个构造函数,接受您的模型作为参数(或您想要传递给validation器的任何其他内容)。 请记住,您应该在SimpleListValidator类中保留无参数构造函数。