繁体   English   中英

Fluent验证 - 将参数传递给集合验证器

[英]Fluent Validation - pass parameter to collection validator

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

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

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

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

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

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

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

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

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

UPDATE

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM