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

标签 c# asp.net-mvc validation fluentvalidation

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

最佳答案

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

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

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

关于c# - Fluent Validation - 将参数传递给集合验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32247571/

相关文章:

c# - 有没有办法获取 System.Random 的实际状态?

c# - 如何格式化要由 jQuery 序列化的 javascript 日期

c# - 获取chrome的控制台日志

.net - 显示不正确的密码信息

javascript - Validator.js - 如何在 NodeJS 中验证字母数字密码?

c# - 哪些列可用于 ml.net 中的预测/输出类

c# - 为什么将 Random.Next() 乘以常量?

c# - Azure 上缺少 mvc dll。怎么了?

c# - 简单项目的组织

php - 使用数组值进行 Javascript 表单验证