使用 Fluent 验证的条件验证

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

前女友。我有一个下拉菜单和一个相关的日期字段。如果没有设置任何字段,则表单应该通过验证。但是,如果两个字段中的一个已经设置,而另一个没有,那么验证应该触发,需要设置另一个字段。

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

78664 次浏览

Fluent validation supports conditional validation, just use the When clause to check the value of the secondary field:

https://docs.fluentvalidation.net/en/latest/conditions.html

Specifying a condition with When/Unless The When and Unless methods can be used to specify conditions that control when the rule should execute. For example, this rule on the CustomerDiscount property will only execute when IsPreferredCustomer is true:

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

The Unless method is simply the opposite of When.

You may also be able to use the .SetValidator operation to define a custom validator that operates on the NotEmpty condition.

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

If you need to specify the same condition for multiple rules then you can call the top-level When method instead of chaining the When call at the end of the rule:

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

This time, the condition will be applied to both rules. You can also chain a call to Otherwise which will invoke rules that don’t match the condition:

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