Monday, April 5, 2010

Using CompareValidator for Date entries

I've written more than a few web pages, and spent a ton of my time looking for date validation that works on both client and server side.

The solution was pretty simple really. It was already there, and I just missed it.

You can accomplish the task by using a simple ASP.NET validation CompareValidator:

Basic textbox date validation


<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Invalid Date" ControlToValidate="dtbRaw" Type="Date" Operator="DataTypeCheck" Display="Dynamic"></asp:CompareValidator>

The relevant parts:
ControlToValidate=ASP.NET Textbox control to be validated
Type=Date
Operator=DataTypeCheck

Validation that the date entry is less than the current date


<asp:CompareValidator ID="CompareValidator2" runat="server" ControlToValidate="dtbRaw"
Display="Dynamic" ErrorMessage="CompareValidator" Operator="LessThan" Type="Date"
></asp:CompareValidator>

The relevant parts:
Operator=LessThan
Type=Date
ValueToCompare=Date to use
Note: If you want to use the current date, then I recommend putting the ValueToCompare in the codebehind.

Resources:
.NET Framework Class Library

Note: I have no researched alternate date formats and/or internationalization.

No comments: