Range validation with nullable types

Oct 24, 2014 at 12:55 PM
When using the Range validation attribute with a nullable type such as int?, should the Range validator not validate a null value as the Required validator should be used to check for this.

DAValidation errors, as it try's to convert the null value to the OperandType. Should it not have a check to see if the value is null?

Suggested change in DataAnnotationsValidator;
protected override bool EvaluateIsValid()
        {
            object value = GetControlValidationValue(ControlToValidate);
            foreach (ValidationAttribute validationAttribute in ValidationAttributes)
            {
                // Here, we will try to convert value to type specified on RangeAttibute. 
                // RangeAttribute.OperandType should be either IConvertible or of built in primitive types
                var rangeAttibute = validationAttribute as RangeAttribute;
                if (rangeAttibute != null && value != null)
                {
                    value = Convert.ChangeType(value, rangeAttibute.OperandType, CultureInfo.CurrentCulture);
                }

                if (validationAttribute.IsValid(value)) continue;
            
                ErrorMessage = validationAttribute.FormatErrorMessage(DisplayName);
                return false;
            }

            return true;
        }
Coordinator
Oct 25, 2014 at 9:18 AM
Edited Oct 25, 2014 at 9:20 AM
Yes, this is a bug. Also I don't remember why I've put this special case for RangeAttribute. According to my fresh tests (I haven't seen this code in a more than a year) this if check is redundant.

The implementation of RangeAttribute.IsValid takes empty string case into account and returns true:
override bool IsValid(object value) {
...
    // Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty.
    if (value == null) {
       return true;
    }
...
Same applies to the RangeValidator.EvaluateIsValid implementation:
protected override bool EvaluateIsValid() {
...
// Special case: if the string is blank, we don't try to validate it. The input should be
// trimmed for coordination with the RequiredFieldValidator.
if (text.Trim().Length == 0) {
    return true;
}
...
I will update the code and nuget package on this weekends. For now you can just remove this if check from your sources copy.
Oct 27, 2014 at 8:20 AM
Thanks for the confirmation and quick update amanek!