Friday 30 October 2009

Asp.Net: Validating data type using CompareValidator

CompareValidator, as the name says, is mainly used to compare value of specified control against value of another control, constant, etc. You can specify the operator that can be used in comparison so you are not limited to checking equality. The following example demonstrates simple comparison of int values (max > min):

Min: <asp:TextBox ID="TextBox1" runat="server"/><br />
Max: <asp:TextBox ID="TextBox2" runat="server"/>
<asp:CompareValidator
ID="CompareValidator1"
runat="server"
ControlToCompare="TextBox1"
ControlToValidate="TextBox2"
ErrorMessage="Max must be greater than Min"
Operator="GreaterThan"
Type="Integer">
</asp:CompareValidator><br />
<asp:Button ID="Button1" runat="server" Text="Submit" />

Which results in:
Results of comparison against different control

Validating data type
Except the basic functionality CompareValidator supports validation of data types. Except the regular operators (Equal, GreaterThan, GreaterThanEqual, LessThan & LessThanEqual) CompareValidator supports an additional one called "DataTypeCheck". It can be used to validate the type of provided value against the type specified in validator. The supported types are: String, Integer, Double, Currency & Date. The validator mainly checks the format of the provided value. In case of Date type it also checks the range (e.g. to ensure that 31st of April is not valid). I like this feature, especially that I've already seen a quite complex custom validator written to do exact this task. Example:

Date: <asp:TextBox ID="TextBox1" runat="server" />
<asp:CompareValidator
ID="CompareValidator1"
runat="server"
ControlToValidate="TextBox1"
ErrorMessage="Invalid date"
Type="Date"
Operator="DataTypeCheck"/>
<asp:Button runat="server" Text="Submit"/>

Which results in:Invalid date provided

Using right format
When validating the type Asp.Net uses the current Page Culture. If you'd like only to accept inputs in specified format you can set the Page Culture property manually. The same date "11.30.2009" will be validated differently for UK and US Cultures (in UK "DD.MM.YYYY" is used, in US it's "MM.DD.YYYY"):

UK:
<%@ Page ... Culture="en-GB"%>

Date invalid for Culture en-GB

US:
<%@ Page ... Culture="en-US"%>

Date valid for Culture en-US

You can also set the page Culture from your code by overriding InitializeCulture() method:

protected override void InitializeCulture()
{
Culture = "en-US";
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture("en-US");

base.InitializeCulture();
}

No comments: