流利的验证-将参数传递给集合验证器 [英] Fluent Validation - pass parameter to collection validator

查看:73
本文介绍了流利的验证-将参数传递给集合验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using fluent validation i ASP.NET MVC application and I've had a problem. This is my rule:

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

我想将x.Type参数传递给SimpleListValidator,我该怎么做?某种扩展方法?看起来应该像这样:

I want to pass x.Type param to SimpleListValidator, how can I do this? Some kind of extension method? It should looks like:

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

推荐答案

为属性设置了集合验证器之后,您可以忘记事实,除了当前正在验证的子模型之外,存在主模型和(n - 1)子模型.而且,没有办法在SetCollectionValidator中将主模型作为参数传递.

After you set collection validator for property - you can forget about fact, that main model and (n - 1) submodels exists except submodel being currently validated. And there is no way to pass main model as a parameter in SetCollectionValidator.

因此,您必须使用RuleForEach方法而不是设置集合验证器:

So you have to use RuleForEach method instead of setting collection validator:

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

我猜想将来可能要告诉孩子验证者事实,即父模型可能存在,但是现在有上面提到的唯一可行的方法.

I guess that possibility to tell child validator about fact, that parent model could exists, should be implemented in future, but right now there is the only working approach, mentioned above.

更新

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

You can create custom ModelBinder, that would set Parent property of each subentity to main entity value, and continue using SetCollectionValidator().

这篇关于流利的验证-将参数传递给集合验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆