There's something out there in life that will delight and amaze you.
Get up, get moving, and go find out what it is. - (Ralph Marston)

Sunday, February 03, 2008

Validate DataTypes using the CompareValidator

Tiny tip on Validation. CompareValidator in ASP.NET, could be used in an effective way such as to validate inputs for either Integer, Double, Date or Currency. Here is how you could do so.

In the CompareValidator, set the ControlToValidate to the input control and set the Type to the expected data type you need to validate, and then set the Operator to the DataTypeCheck. And just leave the ControlToCompare property empty.

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox1" Display="Dynamic" Operator="DataTypeCheck" Type="Date">InValid Date</asp:CompareValidator>

Significant point to note here is, that this validates the Type and not the format of the type. There fore if you expect to specify a format for example, number of decimal points for a double value or specific date format for the date this is not the ideal validation control to go for. (rather uses default date format to check)

But if you need to validate the specific Data Type only,  I think this is a quick and clean way.