How can I use CompareValidator for times without dates?

John MacIntyre picture John MacIntyre · Jan 30, 2009 · Viewed 8.7k times · Source

When I enter 9:00 into the Start control, and 16:00 into Finish; the code below fails validation.

Does anybody know a way I can use the ASP.NET validator for times without the dates?

Start <asp:TextBox ID="txtStart" runat="server" /> (hh:mm)
<br />
Finish <asp:TextBox ID="txtFinish" runat="server" /> (hh:mm)
<br />
<asp:CompareValidator
    id="cpvFinish"
    ControlToValidate="txtFinish"
    ControlToCompare="txtStart"
    Operator="GreaterThanEqual"
    Type="Date"
    Display="Static"
    EnableClientScript="true"
    ErrorMessage="Finish time must be later than the start time."
    runat="server" />

PS-I know I can easily use CustomValidator instead, it just seems like something this validator should be able to handle.

Answer

John MacIntyre picture John MacIntyre · Feb 11, 2009

This appearently cannot be done.

For the record; I used a custom validator.

EDIT: Here's my custom validator code in case anyone (i.e. alhambraeidos) needs it. Please note, this code replaces my sample control names (txtStart & txtFinish) with actual names from my app (txtReady & txtClose).

try
{
    // parse & compare dates
    string randomDt = "01/01/2000 ";
    args.IsValid = DateTime.Parse(randomDt + txtClose.Text) > DateTime.Parse(randomDt + txtReady.Text);
}
catch(Exception /*ex*/)
{
    // exception is assumed to be invalid times entered
    args.IsValid = false;
}