Originally when writing validation logic for strings I settled on using NotEmpty for any string that was required. When using .NotEmpty().Length(min, max) this will cause two errors to be returned instead of just one when an empty string is passed in.
How can the redundant errors be prevented?
.Length(min, max) will not return an error if the string is null, but will return an error when the string is empty and min is greater than 0. There are two ways to implement a required string with a minimum length greater than 0.
The typical way to stop on the first error is to use Cascade method:
RuleFor(o => o.PropertyName)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty() // Will return an error if null or empty
.Length(2, 10) // Will only return an error if length == 1 or > than 10
However for strings, it is easier to read the following:
RuleFor(o => o.PropertyName)
.NotNull()
.Length(2, 10) // Will not return an error on null
String validation scenarios using NotNull, NotEmpty and Length:
Optional with a max length:
RuleFor(o => o.PropertyName).Length(0, max);
Optional with a min and max length:
RuleFor(o => o.PropertyName).Length(min, max);
Required but can have a zero length:
RuleFor(o => o.PropertyName).NotNull()
Required and must have a non-zero length:
RuleFor(o => o.PropertyName).NotEmpty();
Required and has a max length:
RuleFor(o => o.PropertyName).NotNull().Length(0, max);
Required and has a min and max length:
RuleFor(o => o.PropertyName).NotNull().Length(min, max);
Another way to prevent additional errors from occurring would be to set the cascade mode.
RuleFor(x => x.PropName)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.Length(min, max);
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