如何使用类验证属性在属性上动态设置验证消息

时间:2010-04-19 11:17:46

标签: c# asp.net-mvc validation attributes data-annotations

我正在编写Validation属性,该属性位于类上,但会检查类的属性。我希望它在它发现无效的每个属性上设置验证消息。我该怎么做?

这是我到目前为止所得到的:

[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
        }
    }

1 个答案:

答案 0 :(得分:0)

使用the other overload of IsValid可以返回ValidationResult而不是bool