views:

14

answers:

1

How do you get the validation metadata for the built in validation attributes?

I'm trying to implement a word count/character count on a form giving the remaining number allowed. As I am implementing the word count validation and metadata myself (adding it into AdditionalValues) I can access this fine, but having spent ages looking I can't find where to get maximumLength from the StringLength attribute.

A: 

There is no built in way to get the maxLength from the StringLength attribute.

You have to find it manually using reflection, something like:

foreach( var property in model.GetType() )
{
     var stringLengthAttr = property.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault() as StringLengthAttribute;

     if( stringLengthAttr != null )
         return stringLengthAttr.MaximumLength;

}
jfar