'ASP.NET Core Web API - How to implement optional validation using Fluent Validation

I have this validator using Fluent Validation in ASP.NET Core-6 Web API :

public TransactionValidator()
{
    RuleFor(p => p.Token)
        .Cascade(CascadeMode.StopOnFirstFailure);
}

Token should either be null, or it has input value of exactly 6 lengths.

How do I get this done?



Solution 1:[1]

Fluent validation supports predicate validator via Must:

RuleFor(p => p.Token)
    .Cascade(CascadeMode.Stop)
    .Must(s => s == null || s.Length == 6);

Or the same can be achieved with conditions:

RuleFor(p => p.Token)
    .Cascade(CascadeMode.Stop)
    .Length(6)
    .When(c => c.Token != null);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guru Stron