Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enterprise Library Validation Block - Validate nullable properties?

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?

like image 483
Robert MacLean Avatar asked Jan 20 '09 06:01

Robert MacLean


2 Answers

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.

  1. I created a class called IgnoreNullStringLengthValidator that inherits from the StringLengthValidator (here you would inherit the RangeValidator).
  2. Create all the constructors needed to support the base constructors.
  3. Override the DoValidate method and check for a null value - here you would write:

    if (!objectToValidate.HasValue) return;
    
  4. Make sure your next line of code calls base.DoValidate(...).
  5. Created an attribute class called 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.

like image 119
Philippe Avatar answered Oct 21 '22 04:10

Philippe


You could add the IgnoreNulls attribute:

[IgnoreNulls()]
[RangeValidator(0, RangeBoundaryType.Inclusive, 1, RangeBoundaryType.Inclusive)]
int? Age { get; set; }
like image 5
Steven Robbins Avatar answered Oct 21 '22 04:10

Steven Robbins