I want to use the System.ComponentModel.DataAnnotations
assembly to validate arguments (mapped to properties) for a console app I'm working on. 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.
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
). 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.