我需要的是一种有条件地验证字段的方式,取决于是否填充了其他字段。
例如。我有一个下拉列表和一个相关的日期字段。如果没有设置任何字段,则表单应通过验证。但是,如果设置了两个字段中的一个,但另一个字段未设置,则应触发验证,这需要设置另一个字段。
我已经编写了自定义验证类,但它似乎是在单个字段上进行验证。有没有办法使用内置的验证器来设置我需要的验证?如果没有,有没有使用自定义验证器连接两个字段的好方法?
发布于 2011-11-11 05:04:24
Fluent validation支持条件验证,只需使用When子句检查辅助字段的值即可:
https://fluentvalidation.net/start#conditions
使用When /
指定条件when Unless方法可用于指定控制应何时执行规则的条件。例如,仅当IsPreferredCustomer为true时,才会执行CustomerDiscount属性上的以下规则:
RuleFor(customer => customer.CustomerDiscount)
.GreaterThan(0)
.When(customer => customer.IsPreferredCustomer);方法只是与When相反。
您还可以使用.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);
});https://stackoverflow.com/questions/8084374
复制相似问题