0

I'm tring to build a validation rule using FluentValidation lib.

When I use the first part of the code bellows, it works as expected; but when I use the second part, only the first validation is executed, ignoring the last two validation rules.

The second part is not supposed to work? Am I doing something wrong?

// first part -- it works
RuleFor(c => c.Field).RequiredField().WithMessage(CustomMsg1);
RuleFor(c => c.Field).ValidateField().WithMessage(CustomMsg2);
RuleFor(c => c.Field).IsNumeric().WithMessage(CustomMsg3);

// second part -- validates only the first rule
RuleFor(c => c.Field)
    .RequiredField().WithMessage(CustomMsg1)
    .ValidateField().WithMessage(CustomMsg2)
    .IsNumeric().WithMessage(CustomMsg3);
1
  • FluentValidation version: 9.5.3 Commented Dec 16, 2021 at 21:24

1 Answer 1

2

You can specify FluentValidator's cascading behavior with the CascadeMode enum.

You can read more about it here.

The default behavior should be the one you need, but if it works differently without setting the CascadeMode, maybe the default value is globally set somewhere in your project.

Configuring the default value globally looks like this:

ValidatorOptions.Global.CascadeMode = CascadeMode.Stop;

Your code with the default value set above should look something like this:

RuleFor(c => c.Field)
    .Cascade(CascadeMode.Continue)
    .RequiredField().WithMessage(CustomMsg1)
    .ValidateField().WithMessage(CustomMsg2)
    .IsNumeric().WithMessage(CustomMsg3);
Sign up to request clarification or add additional context in comments.

3 Comments

you should mention that CascadeMode.Continue is the default. So you can omit it... I.e the OP's code should work. but it doesn't.
You can set the default behavior globally, maybe it is set to Stop somewhere in his project. But you are right, I edited the answer.
I understand that the cascade mode controls the execution when the validation fails, right? But... using the second part of my code, when the first validation succeed, it doesn't execute the other two validations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.