TypeConversionValidator vs. OnValueConvert

Topics: Validation Application Block
Jun 22, 2007 at 3:08 PM
Edited Jun 22, 2007 at 3:18 PM
Hey all,

I'm just wondering if anyone has a preference on which method is the "better" way to perform type verification for data entered on an ASP.NET page?

To me it seems easier to add a TypeConversionValidator to the properties of an object that you want to verify (especially dates). But are there pros/cons that people have encountered with either of these methods?

We are using a resource file, with template tokens to generate our error messages so we can override the default message so using the Validator appears like the way to go. For example, when verifying the value in a textbox is valid date, we are using a template message defined as: "{1} must be a valid date.". We have similar messages defined for the other common datatypes.

I see that this has been discussed in other posts, but those don't really get into which method is better for the various situations.

Other threads:


Jun 25, 2007 at 11:35 AM
Edited Jun 25, 2007 at 11:37 AM
TypeConversionValidator is IMHO for scenarios where you have string property and you want to be sure that text contained in that property is convertible to other data type.
For me, it seem ridiculous to create "shadow" property of type string for every typed property in my entity.

My aproach to this problem is by using OnValueConvert event, which you must use anyway when using properties of type DateTime etc.
I have multiple methods (for various types) in the page base class and using thouse methods i'm able to check if entered value can by converted to destination type.
Sample of one of these methods follows


protected void ConvertToDateTime(object sender, ValueConvertEventArgs e)
// value can be empty - use NotNullValidator if you need non empty value
if (string.IsNullOrEmpty((string)e.ValueToConvert))
e.ConvertedValue = null;

DateTime convertedValue;
if (DateTime.TryParse((string)e.ValueToConvert, out convertedValue))
e.ConvertedValue = convertedValue;
e.ConversionErrorMessage = Resources.Messages.NotValidDate;