Monday, November 14, 2011

Check Date with CompareValidator

Asp.net provides validation controls to compare data between 2 controls or from a default value. The control responsible for this comparison is called CompareValidator and is represented as <asp:CompareValidator /> element.

The important attributes of this control are:
  • ErrorMessage: to display a custom error message.
  • ControlToCompare: ID of the control to compare against.
  • ControlToValidate: ID of the control that needs to be validated.
  • Operator: type of comparison (GreaterThan, Equal, NotEqual, LessThan, DataTypeCheck, GreaterThanEqual, LessThanEqual are valid values).
  • Type: type of value to compare against (Integar, Double, String, Date, Currency are valid values).
  • ValueToCompare: default value to compare.

The DataTypeCheck operator checks for the type of the data.

In the following example, I will show how to add a CompareValidator control apply it to a TextBox and set the ValueToCompare from code-behind to check if the TextBox contains a date that is greater than today's date.

The main page is below:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="CompareValidator"
Operator="GreaterThan" Type="Date"></asp:CompareValidator>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>


The code behind is below.
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.Date.ToShortDateString());
CompareValidator1.ValueToCompare = DateTime.Now.Date.ToShortDateString();
}



In the code behind, I am setting the ValueToCompare property to current date. Note that, the type of data to compare against is Date and not DateTime - therefore, I am using the ToShortDateString() method to get the date.