Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation NotEmpty message is not showing

For example, FluentValidation validates an empty email address that a user inputs.

I chained two functions but it skips the .NotEmpty().WithMessage() and jumps to the next which is EmailAddress().WithMessage().

RuleFor(r => r.EmailAddress)
                .NotEmpty().WithMessage("Email address is required.")
                .EmailAddress().WithMessage("Email address is not valid.");

Why is that the error message is "Email address is not valid." while the first in chain is "Email address is required."?

like image 767
Ryan Avatar asked Feb 26 '26 17:02

Ryan


1 Answers

This is because the last condition is always verified, even if the first rule fails. Try setting the CascadeMode, as described in the documentation, like this:

RuleFor(r => r.EmailAddress)
    .Cascade(CascadeMode.StopOnFirstFailure)
    .NotEmpty().WithMessage("Email address is required.")
    .EmailAddress().WithMessage("Email address is not valid.");
like image 170
BartoszKP Avatar answered Mar 01 '26 05:03

BartoszKP



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!