Using a CompareValidator to check input is a valid date

The CompareValidator can do more than just compare two controls. You can also compare it against several of the main .net data types such as Date, Integer, Double and Currency.

To do this you would set Operator="DataTypeCheck" and instead of setting the ControlToCompare or ValueToCompare attributes as you normally would you use the Type="Date" (or any of the data types I have listed above).

Here is an example page which illustrates a very simple usage of it:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CompareValidatorExample._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>CompareValidator Date Validation</title>
    <form id="form1" runat="server">
            CompareValidator Date Validation</h1>
        <asp:TextBox ID="TextBox1" ValidationGroup="CompareValidatorDateTest" runat="server"></asp:TextBox>
        <asp:Button ID="ButtonSubmit" runat="server" ValidationGroup="CompareValidatorDateTest" Text="Validate Date" /><br />
        <asp:CompareValidator ID="CompareValidator1" Display="dynamic" ControlToValidate="TextBox1"
            Type="Date" Operator="DataTypeCheck" Text="Please enter a valid date" runat="server"
            ValidationGroup="CompareValidatorDateTest" />

The ValidationGroup attribute

Here is another little side-tip; the ValidationGroup attribute that I have spread throughout this code is a great way to avoid confusion later on when you end up with more than one group of form items in a page. If for example you have a login box in the top corner of your page then the ValidationGroup attribute will let you stop the "username required" validator firing when you click the Submit button on this example.

Advanced Validation

The CompareValidator is one of those controls that provides great basic features but quickly runs out of steam when your websites require a little bit more customisation.

Two things to watch out for when using the CompareValidator in this way is that the Date type will take the format of whatever locale the server is running in. As a UK developer I have sometimes found the server running in an American locale when I uploaded the site which flipped the month and day around.

Another caveat is currency validation - no currency symbols allowed!

To get around these limitations you have the option of using regular expressions via the RegularExpressionValidator or going all-out and developing your own validators by inheriting the base class BaseValidator.

Further Reading

No comments :