开发者

How to dynamically set validation messages on properties with a class validation attribute

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);

          开发者_C百科  foreach (var propertyName in _properiesToValidate)
            {
                var propertyValue = properties.Find(propertyName, false).GetValue(value);
                //if value is invalid add message from base
            }

            //return validity
        }
    }


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜