【问题标题】:Conditional Validation using Fluent Validation使用 Fluent Validation 进行条件验证
【发布时间】:2011-12-26 10:18:35
【问题描述】:

我需要的是一种根据是否填写其他字段来有条件地验证字段的方法。

例如。我有一个下拉列表和一个相关的日期字段。如果未设置任何字段,则表单应通过验证。但是,如果两个字段之一已设置但另一个未设置,则应触发验证,要求设置另一个字段。

我已经编写了自定义验证类,但它似乎是在单个字段上验证的。有没有办法使用内置验证器设置我需要的验证?如果没有,有没有使用自定义验证器连接两个字段的好方法?

【问题讨论】:

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


    【解决方案1】:

    Fluent 验证支持条件验证,只需使用 When 子句检查辅助字段的值即可:

    https://fluentvalidation.net/start#conditions

    使用When/Unless 指定条件 When 和Unless 方法可用于指定控制规则何时执行的条件 应该执行。例如,关于 CustomerDiscount 的这条规则 属性只会在 IsPreferredCustomer 为 true 时执行:

    RuleFor(customer => customer.CustomerDiscount)
        .GreaterThan(0)
        .When(customer => customer.IsPreferredCustomer);
    

    除非方法与何时相反。

    您还可以使用 .SetValidator 操作来定义在 NotEmpty 条件下运行的自定义验证器。

    RuleFor(customer => customer.CustomerDiscount)
        .GreaterThan(0)
        .SetValidator(New MyCustomerDiscountValidator);
    

    如果您需要为多个规则指定相同的条件,那么您 可以调用顶级When方法而不是链接When调用 在规则的末尾:

    When(customer => customer.IsPreferred, () => {
       RuleFor(customer => customer.CustomerDiscount).GreaterThan(0);
       RuleFor(customer => customer.CreditCardNumber).NotNull();
    });
    

    这一次,条件将应用于两个规则。你也可以 将调用链接到否则将调用不匹配的规则 条件:

    When(customer => customer.IsPreferred, () => {
       RuleFor(customer => customer.CustomerDiscount).GreaterThan(0);
       RuleFor(customer => customer.CreditCardNumber).NotNull();
    }).Otherwise(() => {
      RuleFor(customer => customer.CustomerDiscount).Equal(0);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多