Using the CompareValidator control to compare user input date with today's date

HelloBD picture HelloBD · Feb 15, 2010 · Viewed 65.9k times · Source

hey..i would like to compare the current date with the date entered by user..however, i'm encountering errors so far..

i tried something like this:

<asp:TextBox id="txtDate1" runat="server" />    
<asp:CompareValidator runat="server" ErrorMessage="The date must be greater than today"
    ControlToValidate="txtDate1" type="date" 
    ValuetoCompare="DateTime.Today.ToShortDateString()" />

and i got an error stating that the value of DateTime.Today.ToShortDateString() of the ValueToCompare property of "" cannot be converted to type 'date' i also tried ValueToCompare="DateTime.Now.Date()" and i got the same error message.

please help me and i greatly appreciate it.

Answer

womp picture womp · Feb 15, 2010

You're just using the ValueToCompare property as a literal string. You need to use ASP tags in it if you want to execute code to get a dynamic value. Try this:

<asp:comparevalidator runat="server" 
  errormessage="The date must be greater than today"
  controltovalidate="txtDate1" type="date" 
  valuetocompare="<%# DateTime.Today.ToShortDateString() %>" />

Then in your Page_Load method, call Page.DataBind().

This will execute the databinder code when the page is loaded, and put the value in between the quotes.