Wednesday, October 18, 2006

 

Using ASP.NET 2.0: CompareValidator Controls

You can use a <asp:CompareValidator> control to validate one control against another or against a fixed value. I spent an hour searching for a way to use one to validate a date that should be greater than or equal to today’s date. My initial attempt was

<asp:CompareValidator ID="cvFromDate " Text=" Date cannot be less than today's date!" ControlToValidate="txtFromDate" Type="Date" Operator="GreaterThanEqual" SetFocusOnError="true" Display="Dynamic" Runat="server" ValueToCompare="<%= DateTime.Today.ToShortDateString() %>" />                       

 



But it did not like the fixed date value. Interestingly, several articles I found said this was possible, but I had no luck getting it to work (I suspect this is due to initialisation and binding event order?). The simple solution is to set this value during the page’s load event:

   if (!IsPostBack)

   {

       cvFromDate.ValueToCompare = DateTime.Now.ToShortDateString();



The final ASP.NET code which also includes a compare validator to check the same control for dates in valid formats is:

<asp:CompareValidator ID="cvFromDate" Text=" Date cannot be less than today's date!" ControlToValidate="txtFromDate" Type="Date" Operator="GreaterThanEqual" SetFocusOnError="true" Display="Dynamic" Runat="server" />  

 

<asp:CompareValidator id="CompareValidator1" Text="Please enter a valid date format." ControlToValidate="txtFromDate" Display="Dynamic" Type="Date" Operator="DataTypeCheck" SetFocusOnError="true" runat="server" />



    

Powered by Blogger