FluentValidation v3: Better handling of Nullable Types
This is part 4 in a post about new features in FluentValidation v3.
- Part 1 – RuleSets
- Part 2 – CustomizeValidatorAttribute
- Part 3 – ASP.NET MVC validation interceptors
- Part 4 – Better handling of Nullable Types
- Part 5 – Conditional validation of collection elements
- Part 6 – Other Features
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);