I needed a RangeValidator for some date-fields on my ASP.NET pages.
The pages are localized and translated… so the date-formats need to change accordingly.
All was well… until I added a minimum and maximum value for the RangeValidator… something like 1-1-1900 and 1-1-2100.
I got a really cool error:
The value ‘1-1-1901’ of the MaximumValue property of ‘rangevalidatorStartDate’ cannot be converted to type ‘Date’.
So I figured… I need to localize the Min and Max date-string:
So I added this in the code behind.
rangevalidatorStartDate.MinimumValue = DateTime.MinValue.AddYears(1900).ToShortDateString();
The error was not fixed yet… because… you need to localize the parsing of the date according to Culture of the page.
Then the code looks like this.
protected
void Page_Load(object sender, EventArgs e)
{
IFormatProvider culture = new
CultureInfo(Session[“MyCulture”].ToString(), true);
string minDate = DateTime.Parse(DateTime.MinValue.AddYears(1900).ToShortDateString(), culture).ToShortDateString();
string maxDate = DateTime.Parse(DateTime.MinValue.AddYears(2100).ToShortDateString(), culture).ToShortDateString();
rangevalidatorStartDate.MinimumValue = minDate;
rangevalidatorStartDate.MaximumValue = maxDate;
}
Then the markup looks like this.
<td><asp:TextBox
ID=”txtStartDate” runat=”server”
/>
<asp:RequiredFieldValidator
ID=”StartdateFieldValidator” runat=”server”
ControlToValidate=”txtStartDate”
ForeColor=”red”
ErrorMessage=””
Text=”*”
Display=”Dynamic”
CssClass=”validation-message” Width=”7px”
/>
<asp:RangeValidator
runat=”server”
ID=”rangevalidatorStartDate”
Type=”Date”
ControlToValidate=”txtStartDate”
ErrorMessage=”<%$Resources:eService,entityeditor_invaliddatemessage%>“
Display=”None”
/>
</td>