compareValidator use with DateTime

I have been refactoring my colleague code recently. His code does the following, get user filter inputs and two dates for defining data within that two dates is retrieved.
I told him to use the AjaxToolKit calendarExtender and he did. He then does a lot checking in server-side to validate the user input dates. It is okay but with two points I think we can make some improvement.We should have client-side validation to improve user experience and clean up those code-behide checkings cause those if…return is making a big mess.

I rather use the compareValidator to do those dirty work for me and so I do. Here is two common techniques, check if the date is validate and check the begin date must be previous to the end date.

1. Check validate date : Type=”Date” and Operator=”DateTypeCheck”

<asp:CompareValidator ID="vld_startDate" runat="server" ErrorMessage="invalid date format" Type="Date"
                        Operator="DataTypeCheck" ControlToValidate="tb_startDate"></asp:CompareValidator>

2. Compare two date : Type=”Date”, Operator=”LessThanEqual”, i.e ControlToValidate LessThanEqual to ControlToCompare

<asp:CompareValidator ID="vld_compareDate" runat="server" ErrorMessage="begin date must be smaller than end date"
                        Type="Date" ControlToValidate="tb_startDate" ControlToCompare="tb_endDate" Operator="LessThanEqual"></asp:CompareValidator>

These techniques are simple but comes handy when you need them. Cheers.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s