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

发布于 2024-08-29 01:42:40 字数 923 浏览 6 评论 0原文

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木有鱼丸 2024-09-05 01:42:40

使用 IsValid 的另一个重载可以返回 ValidationResult< /a> 而不是 bool

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文