简体   繁体   中英

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. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM