Search code examples
c#.netfluentvalidation

Validate if parameter is equal to one of the given conditions - nullable input given. The null is a valid condition too


I'm trying to validate/check if the parameter x.Size is equal to one of the given conditions above.

The issue is that Size is string[]? and conditions.Contains(x); expects x to be non nullable string. By the way, if Size is null, should be a valid condition too.

public string[]? Size { get; }

public sealed class GetProductsQueryValidator : AbstractValidator<GetProductsQuery>
{
    public GetProductsQueryValidator()
    {
        var conditions = new List<string> { "m", "l", "s" };

        RuleFor(x => x.Size)
            .Must(x => conditions.Contains(x)) // compile-time error: x is expected to be non nullable
            .WithMessage($"Please only use: {string.Join(",", conditions)}");
    }
}

Solution

  • You can use .When for this:

    RuleFor(x => x.Size)
        .ForEach(i => i
            .Must(iv => conditions.Contains(iv!))
            .WithMessage($"Please only use: {string.Join(",", conditions)}")
            .When(iv => iv != null)
        )
        .When(x => x.Size != null);
    

    Note that we need to apply a condition for each array item using ForEach.

    That way it will only evaluate the condition when Size isn't null, and only evaluates the item condition when the item isn't null.