[英]Custom Validation Attribute using Reflection?
I want to use the System.ComponentModel.DataAnnotations
assembly to validate arguments (mapped to properties) for a console app I'm working on. 我想使用System.ComponentModel.DataAnnotations
程序集来验证正在使用的控制台应用程序的参数(映射到属性)。 I'll be using the "buddy class" metadata pattern; 我将使用“伙伴类”元数据模式; it's worked well for me in the past. 过去对我来说效果很好。
One of the things I need to validate is that exactly one of two types of arguments are provided. 我需要验证的一件事是恰好提供了两种类型的参数之一。 In other words, argument foo
can be specified, or argument bar
, but not both, and not neither. 换句话说,可以指定参数foo
或参数bar
,但不能两者都指定,也不能两者都指定。
To this end I started writing a custom validation attribute, which seemed fairly straightforward, but I got a bit lost when I realized I needed to reach outside the property of the validation context, and traverse to a sibling property in the object I am validating (like the CompareAttribute
). 为此,我开始编写一个自定义的验证属性,这似乎很简单,但是当我意识到需要到达验证上下文的属性之外并遍历要验证的对象中的同级属性时,我有点迷惑(例如CompareAttribute
)。 It seems this is a classic reflection case, but I am scratching my head as to how to proceed. 看来这是一个经典的反思案例,但我正在摸索如何进行。 This is what I have so far: 这是我到目前为止的内容:
/// <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.
}
}
Some assistance here would be appreciated. 这里的一些帮助将不胜感激。
Examining other properties with an attribute isn't all that easy. 检查带有属性的其他属性并非易事。 Other people on here have asked the same question (as seen in this link) and the answer's, well, not super pretty. 这里的其他人也问过同样的问题(如本链接所示) ,答案不是很漂亮。 Another answer on here recommends using IDataErrorInfo to perform full class validation . 关于此的另一个答案建议使用IDataErrorInfo执行完整的类验证 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.