有条件地验证收集

Ian*_*ton 4 c# fluentvalidation

public class ProspectValidator : AbstractValidator<Prospect>
{
    public ProspectValidator()
    {   
        RuleFor(p => p.CompetitorProducts)
            .NotNull()
            .When(p => !p.ExistingCustomer);

        RuleFor(p => p.CompetitorProducts.Count)
            .GreaterThan(0)
            .When(p => p.CompetitorProducts != null && !p.ExistingCustomer);
    }
}
Run Code Online (Sandbox Code Playgroud)

该验证器检查是否ExistingCustomer为false,则不CompetitorProducts为null并具有至少一个元素。

它可以工作,但是有可能将其写为一条规则吗?

bpr*_*ard 5

您有两个选项可以在单个命令中执行此操作,但是它们都有些棘手,因为您需要在验证包含类不为null的同时验证内部属性。它们都围绕该Cascade属性旋转(请参阅“设置级联模式”)以停止对第一个错误的验证。

首先,您可以Must用来进行验证。您需要WithMessage像我所做的那样指定一个,以避免获得通用的“竞争对手产品未满足指定的条件”。错误。您可能还想覆盖,WithErrorCode因为它默认为Predicate。请注意,这只会在第二次验证错误时显示;第一个错误仍会正确返回该属性不能为null的消息。

RuleFor(p => p.CompetitorProducts)
  .Cascade(CascadeMode.StopOnFirstFailure)
  .NotNull()
  .Must(p => p.Count > 0)
  .WithMessage("{PropertyName} must be greater than '0'")
  .When(p => !p.ExistingCustomer);
Run Code Online (Sandbox Code Playgroud)

其次,您可以为CompetitorProducts整个类提供一个验证器。这将使您可以FluentValidation管理错误消息和代码。如果您必须在类上进行其他验证,则此方法会很好地工作,但是如果您只需要验证单个属性,则可能会过大。

  public class ProspectValidator: AbstractValidator<Prospect>
    {
        public CurrentUserValidator()
        {
            RuleFor(p => p.CompetitorProducts)
              .Cascade(CascadeMode.StopOnFirstFailure)
              .NotNull()
              .SetValidator(new CompetitorProductsValidator())
              .When(p => !p.ExistingCustomer);
        }
    }

    public class CompetitorProductsValidator : AbstractValidator<Prospect.CompetitorProducts>
    {
        public CompetitorProductsValidator()
        {
            RuleFor(p => p.Count)
              .GreaterThan(0);
        }
    }
Run Code Online (Sandbox Code Playgroud)