How to call ValidationAttributes manually? (DataAnnotations and ModelState)

时光总嘲笑我的痴心妄想 提交于 2019-11-30 05:05:16

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4426854/how-to-call-validationattributes-manually-dataannotations-and-modelstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!