I am trying to come up with a validation for a nullable property, like int.
Example
[RangeValidator(0, RangeBoundaryType.Inclusive, 1, RangeBoundaryType.Inclusive)]
int? Age { get; set; }
However if I set Age
to null validation fails because it doesn't fall in the range, I know I need an [ValidatorComposition(CompositionType.Or)]
as well, but what else should I use?
While the IgnoreNulls
attribute can be added, it leads to convoluted ValidationResults
when validation results are returned. This is because the validation block implicitly wraps the validators into an OrCompositeValidator
- the property can be null OR it can be an integer in the range specified.
When the validation fails, the top-level validation result is for the OrCompositeValidator
. To get the actual RangeValidator
validation result, you now need to drill down into the NestedValidationResults
property on the ValidationResult
object.
This seems like a lot of work to process validation result messages, so it seemed to me that there had to be a better way.
Here is what I did.
IgnoreNullStringLengthValidator
that inherits from the StringLengthValidator
(here you would inherit the RangeValidator
).Override the DoValidate
method and check for a null value - here you would write:
if (!objectToValidate.HasValue) return;
base.DoValidate(...)
.IgnoreNullStringLengthValidatorAttribute
that returns the new IgnoreNullStringLengthValidator
. Here, you would create an IgnoreNullRangeValidatorAttribute
class.The resulting validation result is much more in line with what you'd expect because it does not nest your validators implicitly.
You could add the IgnoreNulls attribute:
[IgnoreNulls()]
[RangeValidator(0, RangeBoundaryType.Inclusive, 1, RangeBoundaryType.Inclusive)]
int? Age { get; set; }
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