Using Validation Attribute Values to Set Control Properties

Topics: Validation Application Block
Sep 13, 2007 at 8:17 PM
All the properties in my object have validation attributes assigned. I would like to use some of those attribute values to update specific properties for certain contorls. For example, assume the following property within a class (clsPerson):

string _lastName;

StringLengthValidator(1, 50)
public string LastName
get { return _lastName; }
set { _lastName = value; }

I would like to be able to retrive the upperBound and use it to set the MaxLength property of the textbox. If I create my own Validator and Attribute (let's call it MyStringLengthValidator), then I can expose the upperBound and lowerBound as public properties. Then on the WinForm I can use Reflection to retrieve the property as follows:

object propertyAttributeValue = null;
PropertyInfo propertyInfo;

// Get the property info for the Assay Property
propertyInfo = typeof(clsPerson).GetProperty("LastName");

// Get the My String Length Validator Attribute (if it exists)
if (propertyInfo .GetCustomAttributes(typeof(MyStringLengthValidatorAttribute), false).Length > 0)
propertyAttributeValue = propertyInfo.GetCustomAttributes(typeof(MyStringLengthValidatorAttribute), false)0;

// If My String Length Validator Attribute exists
if (propertyAttributeValue != null)
// Then set the MaxLength Property for the TextBox control
MyTextBoxControl.MaxLength = ((MyStringLengthValidatorAttribute)propertyAttributeValue).UpperBound;

I think this would make for a much nicer user interface. Is it wrong for the presentation layer to know about the Attribute data assigned to a property? Is there a better way to get this information then rewriting all the existing Validators? I know that RangeValidatorData<T> has UpperBound and LowerBound public properties. But, I don't know if it is possible to get that data based on attribute data. Am I looking at this incorrectly? I'm still pretty new with the Validation Application Block.

Thanks for any help you can provide.