How to dynamically set validation messages on properties with a class validation attribute
Posted
by Dan
on Stack Overflow
See other posts from Stack Overflow
or by Dan
Published on 2010-04-19T11:17:45Z
Indexed on
2010/04/19
11:23 UTC
Read the original article
Hit count: 268
I'm writing Validation attribute that sits on the class but inspects the properties of the class. I want it to set a validation message on each of the properties it finds to be invalid. How do I do this?
This is what I have got so far:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class LinkedFieldValidationAttribute : ValidationAttribute
{
private readonly string[] _properiesToValidate;
public LinkedFieldValidationAttribute(params string[] properiesToValidate)
{
_properiesToValidate = properiesToValidate;
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
foreach (var propertyName in _properiesToValidate)
{
var propertyValue = properties.Find(propertyName, false).GetValue(value);
//if value is invalid add message from base
}
//return validity
}
}
© Stack Overflow or respective owner