【问题标题】:Fluent Validation - pass parameter to collection validatorFluent Validation - 将参数传递给集合验证器
【发布时间】:2015-08-27 10:58:34
【问题描述】:

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

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

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

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

【问题讨论】:

  • 嗨,什么是 SimpleListValidator?问题中缺少什么?
  • 我觉得没关系。这是我想在我的列表中应用的某种验证器,但是这个“SimpleListValidator”在构造函数中需要一个参数,就是这种情况。现在我无法传递 lambda 表达式“x => x.Type”,而且我不知道如何构建像 SetCollectionValidator 这样的适当扩展方法。
  • 如果我理解正确,SimpleListValidator CTOR 得到 1 个参数:类型,如果是:考虑使用 typeof(X): new SimpleListValidator(typeof(x))。它会起作用吗?
  • 但是 x.Type 不是对象类型,这是类中的一个字段(枚举),它可以是任何其他字段等 x.Name, x.Age..
  • 你能粘贴 SimpleListValidator CTOR..

标签: c# asp.net-mvc validation fluentvalidation


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    为属性设置集合验证器后 - 您可以忘记事实,除了当前正在验证的子模型之外,主模型和 (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
    

    我想告诉子验证器这个事实的可能性,即父模型可能存在,应该在将来实现,但现在只有上面提到的唯一可行的方法。

    更新

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

    【讨论】:

    • 太好了,这就是我要找的东西 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    相关资源
    最近更新 更多