Search code examples
c#validationfluentvalidation

Fluent validation stop after first failure


I already know (like well explained in this other question Using CascadeMode.StopOnFirstFailure on a validator level) that the cascade model of the Fluent Validation works only at Rule level and not at Validator level.

I have a task like this:

RuleFor(x => x.Name)
    .NotNull()
    .Length(1, 128)
    .Must(ChkInput);

When(x => x.CompanyName != "..." ,() =>
{
     RuleFor(x => x)
          ...
});

I don't want to validate the second RuleFor if in the first there is an error. Basically because i'm validating the inputs fields in a page and i prefer to show the error one by one.

I have no way to merge the first validation rules with the second because there are different concepts, obtained by the same page, but differents.

So what i want to understand is this: There is a way to start the second validation rules only if the first rules don't fail? Or maybe i'm not using correctly the fluent validation, and even if i'm retrieving all my parameters from the same page i have to separate them and use two (or more, based on the number of the concepts) different validator?


Solution

  • You can add a .When(ThisIsTheFirstFailure) rule using a private local variable, but this won't work if you use singleton validators.

    e.g.

    RuleFor(x => x.Name)
        .NotNull()
        .Length(1, 128)
        .Must(ChkInput);
    
    When(x => x.CompanyName != "..." ,() =>
    {
        RuleFor(x => x.Abc)
            .When(ThisIsTheFirstFailure)
            ...
        RuleFor(x => x.Def)
            .When(ThisIsTheFirstFailure)
            ...
    });