Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ValidationAttributes manually? (DataAnnotations and ModelState)

We have a need within some of our logic to iterate through the properties of a model to auto-bind properties and want to extend the functionality to include the new dataannotations in C# 4.0.

At the moment, I basically iterate over each property loading in all ValidationAttribute instances and attempting to validate using the Validate/IsValid function, but this doesn't seem to be working for me.

As an example I have a model such as:

public class HobbyModel
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "Do not allow empty strings")]
    [DisplayName("Hobby")]
    [DataType(DataType.Text)]
    public string Hobby
    {
        get;
        set;
    }
}

And the code to check the attributes is:

object[] attributes = propertyInfo.GetCustomAttributes(true);
TypeConverter typeConverter =
TypeDescriptor.GetConverter(typeof(ValidationAttribute));

bool isValid = false;
foreach (object attr in attributes)
{
   ValidationAttribute attrib = attr as ValidationAttribute;

   if (attrib != null)
   {
     attrib.Validate(obj, propertyInfo.Name);
   }
}

I've debugged the code and the model does have 3 attributes, 2 of which are derived from ValidationAttribute, but when the code passes through the Validate function (with a empty or null value) it does thrown an exception as expected.

I'm expecting I'm doing something silly, so am wondering whether anyone has used this functionality and could help.

Thanks in advance, Jamie

like image 398
Jamie Avatar asked Dec 13 '10 08:12

Jamie


People also ask

How do you validate model data using DataAnnotations attributes?

ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.

What ModelState is IsValid validate?

Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5. Web API controllers don't have to check ModelState. IsValid if they have the [ApiController] attribute.


2 Answers

This is because you are passing the source object to the Validate method, instead of the property value. The following is more likely to work as expected (though obviously not for indexed properties):

attrib.Validate(propertyInfo.GetValue(obj, null), propertyInfo.Name);

You would certainly have an easier time using the Validator class as Steven suggested, though.

like image 194
Mac Avatar answered Nov 15 '22 08:11

Mac


You do use the System.ComponentModel.DataAnnotations.Validator class to validate objects.

like image 31
Steven Avatar answered Nov 15 '22 07:11

Steven