The value '' of the MaximumValue property of 'RangeValidator1' cannot be converted to type 'Date'.

I ran into a stupid problem tonight when working on an ASP.NET site and I thought i’d share the very obvious answer I ran into…

Essentially, I was adding a textbox with an asp.net ajax control toolkit calendar extender to my form. I needed to ensure that a date, prior to today’s date, could not be selected – a pattern pretty common in web apps. To do so I added a range validator to the form and added a minimum value of today’s date to the page load event in the codebehind.

<asp:TextBox runat="server" ID="txtDate" />
<asp:ImageButton runat="Server" ID="iEndDate" 
ImageUrl="~/images/Calendar_scheduleHS.png"
AlternateText="Click to show calendar" />
               
<ajaxToolkit:CalendarExtender ID="cEndDateButtonExtender"
runat="server"
TargetControlID="txtDate"
PopupButtonID="iEndDate" />
<asp:RangeValidator ID="RangeValidator1" runat="server" 
ControlToValidate="txtDate" 
ErrorMessage="You cannot choose a date prior to today" 
Type="Date" />


 



protected void Page_Load(object sender, EventArgs e)
{
RangeValidator1.MinimumValue = System.DateTime.Now.ToShortDateString();
    
}


Upon loading the web page, I received the following error:




The value '' of the MaximumValue property of 'RangeValidator1' cannot be converted to type 'Date'.




The solution is obvious – but eluded me for about 5 minutes…the RangeValidator does as it’s name suggests – it validates a range. I provided only a MinimumValue and no maximum value and the code was attempting to validate between two bounds. This was a conscious design decision on Microsoft’s part, and one which I fully understand. A bug report was logged and swiftly closed on the MSFT Connect site with a representative suggesting the following fix:




As an alternative you can derive from RangeValidator and override the property ControlPropertiesValid. In the custom implementation just call base.ControlPropertiesValid(). This will have the effect of skipping the additional internal validation step that currently triggers an exception. You will also need to override EvaluateIsValid for the case where either MinimumValue or MaximumValue are outside of the expected range - otherwise the internal evaluation logic will always fail when it attempts to convert String.Empty or a very large value to an integer.

Post a Comment

Popular posts from this blog

Getting Started with Mirth (Part 2)

Mirth

Visual Studio 2012–Debug in Chrome Incognito Mode