使用Fluent验证进行条件验证

The*_*eek 67 .net c# validation asp.net-mvc fluentvalidation

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

防爆.我有一个相关的下拉列表和日期字段.如果没有设置任何字段,则表单应通过验证.但是,如果设置了两个字段中的一个但另一个未设置则应激活验证,则需要设置其他字段.

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

Den*_*her 100

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

http://fluentvalidation.codeplex.com/wikipage?title=Customising&referringTitle=Documentation&ANCHOR#WhenUnless

使用When/unless指定条件 When和unless方法可用于指定控制规则何时应执行的条件.例如,CustomerDiscount属性上的此规则仅在IsPreferredCustomer为true时执行:

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

除非方法与When相反.

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

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