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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With