Monday, August 15, 2011

asp RangeValidator cannot convert MaximumValue in foreign Cultures

Recently I added a range validator to 1 of our controls which is supposed to ensure that a value is between 0.1 - 50. In our application's default culture (which is en-GB) the validator works fine.

However during our localization exercise we realized that the validator throws an exception for certain cultures (in this case, when we ran the application in de-DE)

The declaration of my control is as follows:

< asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="SomeTextBox1" MinimumValue="0.1" MaximumValue="50" Type="Double" />


The runtime exception that was thrown was:

The value '0.1' of the MinimumValue property of 'RangeValidator1' cannot be converted to type 'Double'.
at System.Web.UI.WebControls.RangeValidator.ValidateValues()
at System.Web.UI.WebControls.RangeValidator.ControlPropertiesValid()
at System.Web.UI.WebControls.BaseValidator.get_PropertiesValid()
at System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e)

Reason:

Well its simple. German's equivalent of 0.1 is 0,1 (with a comma instead of a dot). And when the thread is running in the german culture, it doesn't know how to convert 0.1. IMO, this is a bug in the framework. The range validator (or any other control for that matter) must not consider the culture for values that are set during design time.

Solution:

What i did was;

Replace
MinimumValue="0.1"
with
MinimumValue='<%# (0.1).ToString(System.Globalization.CultureInfo.CurrentCulture) %>'

This way, I'm not hardcoding anything in design time. during run time the value will be set to the control in the current thread's culture. You can also do this in code behind. But I didn't have the option of recompiling the library :)