Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation string NotNull versus NotEmpty

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?

like image 847
Brett Allen Avatar asked Jan 29 '14 19:01

Brett Allen


2 Answers

.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);
like image 144
Brett Allen Avatar answered Oct 04 '22 19:10

Brett Allen


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);
like image 37
bschreck Avatar answered Oct 04 '22 19:10

bschreck