CodeNoob
CodeNoob

Reputation: 411

Access property values with an attribute

How do I access the value of a property inside an attribute class. I'm writing a custom validation attribute that needs to check the value of the property against a regular expression. The For Instance:

public class MyAttribute
{
public MyAttribute (){}

//now this is where i want to use the value of the property using the attribute. The attribute can be use in different classed
public string DoSomething()
{
//do something with the property value
}
}

Public class MyClass
{
[MyAttribute]
public string Name {get; set;}
}

Upvotes: 2

Views: 102

Answers (1)

Ian Routledge
Ian Routledge

Reputation: 4042

If you just want to use a regular expression validation attribute, then you can inherit from RegularExpressionAttribute, see https://stackoverflow.com/a/8431253/486434 for an example of how to do that.

However, if you want to do something more complex and access the value you can inherit from ValidationAttribute and override the 2 virtual methods IsValid. E.g.:

public class MyAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // Do your own custom validation logic here
        return base.IsValid(value);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return base.IsValid(value, validationContext);
    }
}

Upvotes: 1

Related Questions