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?
Thanks
CodePudding user response:
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);