8

I have some data annotation attribute like this:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]

How I can Find Data Annotation attributes and their parameters using reflection?

thanks

Arian
  • 12,793
  • 66
  • 176
  • 300

1 Answers1

14

I assume you have something like this:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
public string FirstName {get;set;}

To get the attribute and a property from it:

StringLengthAttribute strLenAttr = 
  typeof(Person).GetProperty("FirstName").GetCustomAttributes(
  typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().Single();


int maxLen = strLenAttribute.MaximumLength;
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Anders Abel
  • 67,989
  • 17
  • 150
  • 217