user1075940
user1075940

Reputation: 1125

CascadeMode StopOnFirstFailure doesn't work

public class Validator : AbstractValidator<Query>
        {
            public Validator()
            {
                CascadeMode = CascadeMode.StopOnFirstFailure;

                RuleFor(x => x.A).NotEmpty();
                RuleFor(x => x.B).NotEmpty();
                RuleFor(x => x).MustAsync(...);
            }
        }

I'like to construct validator which dones't call MustAsync when above rules are not met. Unfortunately settings CascadeMode to StopOnFirstFailure in validator doesn't do the work.

Upvotes: 1

Views: 1675

Answers (1)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

As stated by the author

That's the correct behaviour - CascadeMode only affects validators within the same rule chain. Independent calls to RuleFor are separate, and not dependent on the success or failure of other rules.

See this.

So it would apply for this case

Rulefor(x => x.A)
.NotEmpty()
.Length(10);

=> the Length validation would only be applied if A is not empty.

So you'll have to use a When extension in your MustAsync rule, checking if A and B are not empty (or an if around this rule).

Upvotes: 4

Related Questions