有条件的验证使用流利的验证 [英] Conditional Validation using Fluent Validation

查看:230
本文介绍了有条件的验证使用流利的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是一个方法取决于是否有其他领域被填充到有条件地验证领域。

What I need is a way to conditionally validate fields depending on if other fields are filled in.

例。我有一个下拉列表和相关日期字段。如果没有域的设置,则表单应该通过验证。然而,如果两个场中的一个被设置,但在另一种是不那么验证应激发,要求其他字段进行设置。

Ex. I have a dropdown and a date field that are related. If none of the fields are set then the form should pass validation. However, if one of the two fields are set but the other isn't then the validation should fire, requiring the other field to be set.

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

I have written custom validation classes but it seems that it is validates on single fields. Is there a way to set up the validation that I need using the built in validators? If not, Is there a good way to connect two fields using a custom validator?

推荐答案

流利的验证支持有条件的验证,只需使用条款时,检查二次字段的值:

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

<一个href="http://fluentvalidation.$c$cplex.com/wikipage?title=Customising&referringTitle=Documentation&ANCHOR#WhenUnless">http://fluentvalidation.$c$cplex.com/wikipage?title=Customising&referringTitle=Documentation&ANCHOR#WhenUnless

指定使用在/除非的时候除非方法可用于指定条件的控制规则时的条件   应该执行。例如,关于CustomerDiscount这个规则   属性将只执行时preferredCustomer是正确的:

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.CustomerDiscount).GreaterThan(0)。当(客户=>   customer.Is preferredCustomer);`

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

该除非方法是一个简单的当。相反

The Unless method is simply the opposite of When.

您也可以使用.SetValidator操作来定义一个自定义的验证器,工作在NotEmpty条件。

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

RuleFor(客户=>   customer.CustomerDiscount).GreaterThan(0).SetValidator(新MyCustomerDiscountValidator)

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

这篇关于有条件的验证使用流利的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆