Search code examples
c#data-annotations

Is it possible to use the Required ValidationAttribute with value types?


I've decorated a class with:

[Required(ErrorMessage = "Price is required.")]
public decimal Price { get; set; }

But when validating it with code:

   for each (PropertyInfo prop in Me.GetType().GetProperties())
   {
        if (prop.GetIndexParameters().Length = 0)
        {
            for each (ValidationAttribute validatt in prop.GetCustomAttributes(GetType(ValidationAttribute), True))
            {
                if (!validatt.IsValid(prop.GetValue(Me, Nothing))
                {
                    retval.Add(New PropertyValidationError(prop.Name, string.Format("There is a problem with the {0} property. It is flagged with the {1}", prop.Name, validatt.GetType.Name), validatt.ErrorMessage));
                }
            }
        }
    }

I'm finding that a value of 0 is being treated as fulfilling the "requiredness", which is not what I intended (in fact, I wanted to allow any value other than zero) - is it my validation code doing the wrong thing, or is there a way to use decorate with a ValidationAttribute that will fail for default values for value types?


Solution

  • When you're using a value type, such as decimal, it's impossible to not have a value. As such, that attribute is effectively meaningless.

    It would be a better idea to use [Range], as this allows you to specify meaningful values. However, this will not allow you to handle "any non-zero value" (though you could easily handle any positive non-zero value).

    Your criteria, as stated, would require creating a custom validation attribute to validate, as "any value other than default(T)" is not a built-in validation.