Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    });
like image 513
Stan Avatar asked Oct 20 '22 04:10

Stan


1 Answers

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.

like image 181
Neil Smith Avatar answered Oct 22 '22 18:10

Neil Smith