Otherwise I always need to check if the value is null
before performing any other validations. It's kinda annoying if I have many custom checks that are using Must()
.
I placed NotEmpty()
at the very top of it therefore it already returns false, is it possible to stop there?
RuleFor(x => x.Name)
.NotEmpty() // Can we not even continue if this fails?
.Length(2, 32)
.Must(x =>
{
var reserved = new[] {"id", "email", "passwordhash", "passwordsalt", "description"};
return !reserved.Contains(x.ToLowerInvariant()); // Exception, x is null
});
See here. It's called CascadeMode and can be set on an individual rule like this:
RuleFor(x => x.Name)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.Length(2, 32);
Or it can be set globally with:
ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;
Note: if you set it globally, it can be overridden with CascadeMode.Continue
on any individual validator class or on any individual rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With