使用 Fluent Validation 进行条件验证
我需要的是一种根据其他字段是否填写来有条件地验证字段的方法
。我有一个相关的下拉菜单和日期字段。如果未设置任何字段,则表单应通过验证。但是,如果两个字段之一已设置,但另一个未设置,则应触发验证,要求设置另一个字段。
我已经编写了自定义验证类,但它似乎是在单个字段上验证的。有没有办法使用内置验证器来设置我需要的验证?如果没有,是否有使用自定义验证器连接两个字段的好方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Fluent 验证支持条件验证,只需使用 When 子句检查辅助字段的值即可:
https ://docs.fluidation.net/en/latest/conditions.html
您还可以使用 .SetValidator 操作来定义对 NotEmpty 条件进行操作的自定义验证器。
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
You may also be able to use the .SetValidator operation to define a custom validator that operates on the NotEmpty condition.