简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM