3

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?

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166

3 Answers3

5

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.

Community
  • 1
  • 1
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Given I want to have *any value other than zero*; Looks like I mioght have to create a custom attribute? – Rowland Shaw Jun 13 '13 at 16:29
  • @RowlandShaw Yeah - If you want "any positive value" you could use `[Range]`, but for any value, you'd need a custom validation attribute. – Reed Copsey Jun 13 '13 at 16:30
2

What about make you value type variable nullable?

public decimal? Price { get; set; }
Valeriy Lyuchyn
  • 223
  • 4
  • 10
1

Use the range validation attribute.

[Range(min, max, ErrorMessage )]
Maess
  • 4,118
  • 20
  • 29