Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for Attributes From Within the Code of Other Attributes

Is it possible to test for the existence of an attribute within the code of another attribute?

Say you have the following class definition:

public class Inception {
    [Required]
    [MyTest]
    public int Levels { get; set; }
}
public class MyTestAttribute : ValidationAttribute {
    public override bool IsValid(object o){
        // return whether the property on which this attribute
        // is applied also has the RequiredAttribute
    }
}

... is it possible for MyTestAttribute.IsValid to determine whether Inception.Levels has the RequiredAttribute?

like image 436
Pat Newell Avatar asked May 16 '12 19:05

Pat Newell


1 Answers

In the specific case of a ValidationAttribute it is possible, but you have to use the other IsValid overload that has a context parameter. The context can be used to get the containing type and also get the name of the property that the attribute is applied to.

protected override ValidationResult IsValid(object value, 
  ValidationContext validationContext)
{
  var requiredAttribute = validationContext.ObjectType
    .GetPropery(validationContext.MemberName)
    .GetCustomAttributes(true).OfType<RequiredAttribute>().SingleOrDefault();
}
like image 70
Anders Abel Avatar answered Oct 16 '22 02:10

Anders Abel