【问题标题】:Add error message without using WithMessage() method in FluentValidation在 FluentValidation 中不使用 WithMessage() 方法添加错误消息
【发布时间】:2022-03-16 18:46:35
【问题描述】:

我有一个问题,如果有人可以帮助我,我将不胜感激。 我在 ASP.NET 项目中使用“FluentValidation”验证对象,我想知道是否有一种方法可以在不使用 WithMessage () 方法的情况下在“ValidationResult”中添加错误消息。 我需要根据与已验证类的属性无关的条件添加错误消息。 感谢关注。

【问题讨论】:

    标签: c# .net fluentvalidation


    【解决方案1】:

    例如,当您编写自定义验证器时。

    see FluentValidation documentation。您可以在此处看到来自 Visual Studio 的屏幕,其中添加了 ErrorMessage 字符串。这是此类规则的一些实际代码

    RuleFor(customerCreateCommand => customerCreateCommand.Dto.Addresses)
               .Custom((addresses, context) =>
               {
                   bool includesBillingAddress = false;
                   foreach (AddressDto address in addresses)
                   {
                       if (address.AdressTypeId == Commons.Enums.AddressType.Billing)
                       {
                           includesBillingAddress = true;
                       }
                   }
                   if (includesBillingAddress == false) { context.AddFailure("A customer profile needs a billing address"); }
               });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多