2012-02-22 26 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

回答

相關問題