Date Field Validation

In .NET, it is really easy to check whether a user is entering a date into a form field, although it’s not necessarily obvious how to do so. What you need to do is include a CompareValidator in your web form. The code would look like this:

<asp:TextBox ID="txtBirthDate" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
	ErrorMessage="CompareValidator" ControlToValidate="txtBirthDate"
	Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>

The three important properties that you need to set in the CompareValidator are:

  1. ControlToValidate – This is the ID of the Textbox
  2. Operator – Default is “Equal”, need to change to DataTypeCheck
  3. Type – Default is String, set to Date

This will cause the validator to return the error message when an invalid date is entered. It will accept dates such as “4/18/2004”, “9/12/95” and “02/29/2004”, however would cause the error message to be displayed on “14/14/2000”, “02/29/2005”, and “January 1, 2000”. I’d like to see it accept the last one, however, the date should be in the format mm/dd/yyyy, be sure to tell the users to enter this format.

Of course, to be semantically correct, you’d want to give your Textbox a label on the form, and the CompareValidator a more descriptive error message. Also, be sure to enable server side validation, see “Server-Side Validation“.

This tip came from Peter Blum, on dnrTV. Peter has done a ton of work with validation in .NET. His product, Professional Validation and More looks very promising.

%d bloggers like this: