[英]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.
}
}
這里的一些幫助將不勝感激。
檢查帶有屬性的其他屬性並非易事。 這里的其他人也問過同樣的問題(如本鏈接所示) ,答案不是很漂亮。 關於此的另一個答案建議使用IDataErrorInfo執行完整的類驗證 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.