FluentValidation v3: Better handling of Nullable Types

This is part 4 in a post about new features in FluentValidation v3.

In previous versions of FluentValidation, if you wanted to use any of the comparison validators (GreaterThan, LessThan etc) against a nullable type you had to validate the nullable’s Value property in combination with a null check:

RuleFor(x => x.NullableInt.Value).GreaterThan(0).When(x => x.NullableInt != null);

This was necessary because the comparison validators require that the property implement IComparable (which Nullable<T> does not implement). Although this worked, it was somewhat cumbersome and unnecessarily verbose.

With FluentValidation v3, there are additional overloads for all of the comparison validators that work directly with nullables, so the above can be simplifed to:

RuleFor(x => x.NullableInt).GreaterThan(0);
Written on April 29, 2011