Conditionally check collection

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);
    }
}

This validator checks that if it ExistingCustomeris false, then CompetitorProductsit is not null and has at least one element.

It works, but can it be written as one rule?

+4
source share
1 answer

You have two options for this in one command, but they are a bit complicated, since you need to check the internal property, checking that the inclusion class is not null. They both revolve around the property Cascade(see "Cascading Mode Setup") to stop the check on the first error.

-, Must . WithMessage, , " " ". . WithErrorCode Predicate. , ; - , .

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

-, 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);
        }
    }
+4

All Articles