简体   繁体   中英

Is it possible to stop checking further validations when the first one fails?

Otherwise I always need to check if the value is null before performing any other validations. It's kinda annoying if I have many custom checks that are using Must() .

I placed NotEmpty() at the very top of it therefore it already returns false, is it possible to stop there?

Example

RuleFor(x => x.Name)
    .NotEmpty() // Can we not even continue if this fails?
    .Length(2, 32)
    .Must(x =>
    {
        var reserved = new[] {"id", "email", "passwordhash", "passwordsalt", "description"};
        return !reserved.Contains(x.ToLowerInvariant()); // Exception, x is null
    });

See here . It's called CascadeMode and can be set on an individual rule like this:

RuleFor(x => x.Name)
    .Cascade(CascadeMode.StopOnFirstFailure)
    .NotEmpty()
    .Length(2, 32);

Or it can be set globally with:

ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;

Note: if you set it globally, it can be overridden with CascadeMode.Continue on any individual validator class or on any individual rule.

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