使用 Fluent Validation Library for .Net 验证单个属性
您可以使用 Fluent Validation 库仅验证单个属性吗?如果可以,如何验证?我认为2009 年 1 月的这个讨论线程向我展示了如何做到这一点通过以下语法:
validator.Validate(new Person(), x => x.Surname);
不幸的是,这在当前版本的库中似乎不起作用。另一件让我相信验证单个属性是可能的事情是以下引用 Jeremy Skinners 的博客文章:
“最后,我添加了执行 FluentValidation 的一些属性验证器的功能,而无需验证整个对象。这意味着现在可以阻止将默认的“需要一个值”消息添加到 ModelState ”
“最后,我添加了执行 FluentValidation 的一些属性验证器的功能,而无需验证整个对象 我不知道这是否一定意味着它只支持验证单个属性,或者您可以告诉验证库在第一个验证错误后停止验证。
Can you validate just a single property with the Fluent Validation Library, and if so how? I thought this discussion thread from January of 2009 showed me how to do it via the following syntax:
validator.Validate(new Person(), x => x.Surname);
Unfortunately it doesn't appear this works in the current version of the library. One other thing that led me to believe that validating a single property might be possible is the following quote from Jeremy Skinners' blog post:
"Finally, I added the ability to be able to execute some of FluentValidation’s Property Validators without needing to validate the entire object. This means it is now possible to stop the default “A value was required” message from being added to ModelState. "
However I do not know if that necessarily means it supports just validating a single property or the fact that you can tell the validation library to stop validating after the first validation error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 CodePlex 上的此讨论,该功能是通过扩展添加的方法。您需要导入 FluentValidation 命名空间才能使它们显示在 IntelliSense 中。
According to this discussion on CodePlex, that ability is added by way of extension methods. You would need to import the FluentValidation namespace to have those show up in IntelliSense.
对于其他偶然发现这个问题的人。
在 FluentValidation v9.3.0 中,您将执行以下操作:
For anyone else stumbling upon this problem.
In FluentValidation v9.3.0 you would do:
感谢@sebastian.roibu 的回答,我想分享我的解决方案,因为他的答案对我来说并不完整,希望这会节省您解决问题的时间。
我必须首先创建一个单独的 CustomValidator: AbstractValidator 类。
此类具有
Validate()
方法。接下来,Validate() 方法本身将“不执行任何操作”,您需要查看返回 (
ValidationResult
),其中包含来自 ValidationResult 的
CustomValidator
的所有错误我能够获取该 1 属性的所有错误,并将其附加到我当前的上下文中,该上下文没有以这种方式进行验证。这是我关于使用 JsonPatchDocument 验证“PATCH”操作的完整答案:
Thanks to @sebastian.roibu answer, I would like to share my solution as his answer was incomplete for me and hope this will save you time figuring it out.
I had to create a seperate
CustomValidator: AbstractValidator
class first.This class has the
Validate()
method.Next, the Validate() method will "do nothing" on it's own, you need to look at the return (
ValidationResult
) which will have all the errors fromCustomValidator
From ValidationResult I was able to get all the errors for that 1 property, and attach it to my current context that wasn't validating this that way.
Here is my full answer on validating "PATCH" operation using JsonPatchDocument: