Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 731
luke88 Avatar asked Oct 24 '25 15:10

luke88


2 Answers

I had a similar problem. I had two types of validation errors and I wanted to display the second set of errors only if there were no errors in the first set. To accomplish this I separated the two different sets of errors into separate Validation classes and called the second class only if the first class returned with no errors.

like image 50
Dexter Avatar answered Oct 27 '25 05:10

Dexter


Maybe anyone have the same doubtfulness i had using CascadeMode.StopOnFirstFailure, if you use methods like not null or not empty, and your field not have value, NotNull() will count as first error and stops without use my custom message

RuleFor(v => v.Field)
            .NotNull().NotEmpty()
            .WithMessage("field must have value")
            .Must(field => condition true)
            .WithMessage("field must ...")

You can use CascadeMode.StopOnFirstFailure, it works, a message for condition

RuleFor(v => v.Field)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .NotNull()
            .WithMessage("field must have value")
            .NotEmpty()
            .WithMessage("field must have value")
            .Must(field => true)
            .WithMessage("field must ...")

or like this, looks better

    RuleFor(v => v.Field)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .Must(field => string.IsNullOrEmpty(field))
            .WithMessage("field must have value")
            .Must(field => true)
            .WithMessage("field must ...")
like image 28
Felipe Anselmo Avatar answered Oct 27 '25 03:10

Felipe Anselmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!