使用 Fluent Validation Library for .Net 验证单个属性

发布于 2024-09-01 11:51:21 字数 753 浏览 3 评论 0原文

您可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

∞梦里开花 2024-09-08 11:51:21

根据 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.

空心空情空意 2024-09-08 11:51:21

对于其他偶然发现这个问题的人。
在 FluentValidation v9.3.0 中,您将执行以下操作:

_Validator.Validate(ClassInstance, 
                opt=> opt.IncludeProperties(x => x.SomePropertyOfTheClassInstance));

For anyone else stumbling upon this problem.
In FluentValidation v9.3.0 you would do:

_Validator.Validate(ClassInstance, 
                opt=> opt.IncludeProperties(x => x.SomePropertyOfTheClassInstance));
笛声青案梦长安 2024-09-08 11:51:21

感谢@sebastian.roibu 的回答,我想分享我的解决方案,因为他的答案对我来说并不完整,希望这会节省您解决问题的时间。

我必须首先创建一个单独的 CustomValidator: AbstractValidator 类。
此类具有 Validate() 方法。

接下来,Validate() 方法本身将“不执行任何操作”,您需要查看返回 (ValidationResult),其中包含

来自 ValidationResult 的 CustomValidator 的所有错误我能够获取该 1 属性的所有错误,并将其附加到我当前的上下文中,该上下文没有以这种方式进行验证。

这是我关于使用 JsonPatchDocument 验证“PATCH”操作的完整答案:

    public PatchCommandValidator()
    {
        RuleForEach(x => x.JsonPatchDocument.Operations)
            .CustomAsync(HandleOperationValidation);
    }

    private async Task HandleOperationValidation(Operation<BasketHeaderPatchModel> property, ValidationContext<PatchBasketHeaderCommand> context, CancellationToken cancellation)
    {
        var requestModel = new RequestModel();

        var propertyInfo = requestModel.GetType().GetProperty(property.path.Replace("/", ""));
        propertyInfo.SetValue(basketHeaderPatchModel, Convert.ChangeType(property.value, propertyInfo.PropertyType));

        var customValidator = new CustomValidator();

        var result = await customValidator.ValidateAsync(requestModel , x => x.IncludeProperties(propertyInfo.Name), cancellation);

        result.Errors.ForEach(context.AddFailure);

    }

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 from CustomValidator

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:

    public PatchCommandValidator()
    {
        RuleForEach(x => x.JsonPatchDocument.Operations)
            .CustomAsync(HandleOperationValidation);
    }

    private async Task HandleOperationValidation(Operation<BasketHeaderPatchModel> property, ValidationContext<PatchBasketHeaderCommand> context, CancellationToken cancellation)
    {
        var requestModel = new RequestModel();

        var propertyInfo = requestModel.GetType().GetProperty(property.path.Replace("/", ""));
        propertyInfo.SetValue(basketHeaderPatchModel, Convert.ChangeType(property.value, propertyInfo.PropertyType));

        var customValidator = new CustomValidator();

        var result = await customValidator.ValidateAsync(requestModel , x => x.IncludeProperties(propertyInfo.Name), cancellation);

        result.Errors.ForEach(context.AddFailure);

    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文