I'm trying to use an ASP.NET RangeValidator to validate a date on a textbox. The format of the date entered on the textbox is dd MMMM yyyy.

How can I use the range validator to validate a valid date? If I enter 1 January 1000 as the min or max value I get an error saying value cannot be converted to type date, but if I use another format it picks up my entered text as invalid.

Below is my code:

<asp:TextBox runat="server" /> <cc2:CalendarExtender runat="server" TargetControlID="txtDatecompleted" Format="dd MMMM yyyy" /> <asp:RangeValidator runat="server" Type="Date" ControlToValidate="txtDatecompleted" MaximumValue="9999/12/28" MinimumValue="1000/12/28" ErrorMessage="enter valid date" Display="None" /> <cc2:ValidatorCalloutExtender runat="server" Enabled="True" TargetControlID="RangeValidator1"> </cc2:ValidatorCalloutExtender> 
1

4 Answers

Best option would be

Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:

<asp:CompareValidator runat="server" Type="Date" Operator="DataTypeCheck" ControlToValidate="txtDatecompleted" ErrorMessage="Please enter a valid date."> </asp:CompareValidator> 
5

A CustomValidator would also work here:

<asp:CustomValidator runat="server" ControlToValidate="txtDatecompleted" onservervalidate="valDateRange_ServerValidate" ErrorMessage="enter valid date" /> 

Code-behind:

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args) { DateTime minDate = DateTime.Parse("1000/12/28"); DateTime maxDate = DateTime.Parse("9999/12/28"); DateTime dt; args.IsValid = (DateTime.TryParse(args.Value, out dt) && dt <= maxDate && dt >= minDate); } 
3

I think the following is the easiest way to do it.

<asp:TextBox runat="server" Visible="False"></asp:TextBox> <asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator> 

I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.