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