The Importance of Type with a CompareValidator

As a consultant I get pulled back into the wonderful world of ASP.NET Web Forms. I recently had a trip down memory lane with the ASP.NET CompareValidator. I was successfully comparing dates between two different text boxes when I noticed they weren’t comparing correctly if I didn’t set the Type attribute.

For example, “06/01/2015” evaluated properly as before “06/15/2015” unless it was formatted as “6/1/2015.” Why? Because I hadn’t set the Type and it was evaluated as a string.

Setting the Type=Date will properly evaluate the date. Headache averted.

Example:

<asp:CompareValidator
      runat="server"
      Type="Date"
      Operator="DataTypeCheck"
      ControlToValidate="tbDate"
      ErrorMessage="Please enter a valid date."
      Display="Static"/>

Leave a Reply