Search code examples
c#fluentvalidation

Fluent Validation - How to ensure that a collection Count greater than zero when not null, but can be null


I'm struggling to figure out how to define a rule that allows a collection property to be null, but not empty. Providing null for the collection property being a valid use case, but when the collection is provided, the collection needs to have at least one entry. Hence:

// Valid
{
    "codes": null
}

// Invalid
{
    "codes": []
}

// Valid
{
    "codes": ["Pass"]
}

I've been playing around and can't seem to find anything that works:

public class UpdateCodesRequest
{
    public IEnumerable<string> Codes { get; set; } 
}

public class UpdateCodesRequestValidator : AbstractValidator<UpdateCodesRequest>
{
    public UpdateCodesRequestValidator()
    {
        // none of these will work if Codes is null
        RuleFor(x => x.Codes.Count()).GreaterThan(0).When(x => x != null);
        RuleFor(x => x.Codes).Must(x => x.Any()).When(x => x != null);
        RuleFor(x => x.Codes).Must(x => x != null && x.Any()).When(x => x != null);
    }
}

Solution

  • How about this one?

    RuleFor(x => x.Codes).Must(x => x == null || x.Any());