繁体   English   中英

使用反射的自定义验证属性?

[英]Custom Validation Attribute using Reflection?

我想使用System.ComponentModel.DataAnnotations程序集来验证正在使用的控制台应用程序的参数(映射到属性)。 我将使用“伙伴类”元数据模式; 过去对我来说效果很好。

我需要验证的一件事是恰好提供了两种类型的参数之一。 换句话说,可以指定参数foo或参数bar ,但不能两者都指定,也不能两者都指定。

为此,我开始编写一个自定义的验证属性,这似乎很简单,但是当我意识到需要到达验证上下文的属性之外并遍历要验证的对象中的同级属性时,我有点迷惑(例如CompareAttribute )。 看来这是一个经典的反思案例,但我正在摸索如何进行。 这是我到目前为止的内容:

/// <summary>
/// This property, or the other specified, are required, but both cannot be set.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class XORAttribute : ValidationAttribute
{
    /// <summary>
    /// If validation should fail, return this error message.
    /// </summary>
    public string ErrorMessage { get; set; }
    /// <summary>
    /// The name of the other required property that is mutually exclusive of this one.
    /// </summary>
    public string OtherValueName { get; set; }

    public XORAttribute(string otherValueName)
    {
        this.OtherValueName = otherValueName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //Something needs to go here.
    }
}

这里的一些帮助将不胜感激。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM