Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 525
HelloBD Avatar asked Feb 15 '10 05:02

HelloBD


People also ask

Can compare two values of an input control against a value of another input control?

The CompareValidator control is used to compare the input server control's value against another value. The CompareValidator control can compare against a value specified to the validator control or against the value of another input control.

What is Compare Validator control?

Use the CompareValidator control to compare the value entered by the user in an input control, such as a TextBox control, with the value entered in another input control or a constant value.

What are the properties need to set for compare validator?

You can perform this type of form validation by using the CompareValidator control. To compare two dates, you need to set the ControlToValidate, ControlToCompare, Operator, and Type properties of the CompareValidator control.


2 Answers

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.

like image 142
womp Avatar answered Dec 05 '22 04:12

womp


    <asp:CompareValidator ID="CompareValidator3" runat="server" 
                        ControlToValidate="TextBox1" ErrorMessage="Date should be on or after today" 
                        Operator="GreaterThanEqual" Type="Date">
</asp:CompareValidator>

In the page load event set the validator's value to compare as

CompareValidator3.ValueToCompare = DateTime.Now.ToShortDateString();
like image 30
Abhishek kumar Avatar answered Dec 05 '22 05:12

Abhishek kumar