views:

177

answers:

1

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
        }
    }
A: 

Use the other overload of IsValid which can return a ValidationResult instead of a bool.

Craig Stuntz
This seems to be .net 4.0, is there an 3.5 approach?
Dan
I don't know. You could try setting `ErrorMessage`.
Craig Stuntz
ErrorMessage is just a string - there is no way of setting an association, between it and a class property, I don't think?
Dan
Right, because validation is typically done on a property. There's no rule which says you *can't* do it on a class, but it's clear that's not the design intention.
Craig Stuntz
Sure, but this gets back to my question, and the approach I tried above, how do I do it with the class approach?
Dan