2012-02-22 25 views
0

我想使用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. 
    } 
} 

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

+0

真的吗?没有接受者?我会认为这对于在验证过程中经验丰富的人员来说是一个简单的问题。 – 2012-02-22 15:44:17

回答

相关问题