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.
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.
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.
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.
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.
<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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With