Tuesday, May 25, 2010

Datetime Validators for different Cultures



 There are situation when you need datetime validation for a culture that there is in application.
You don’t have the possibility to set the format to the validation because the format differs for en-GB (mm/dd/yy), ro-Ro(dd.mm.yy).

<asp:RangeValidator ID="rvdate" runat="server" ControlToValidate="txtDateStart" ErrorMessage="!" Type="Date" MinimumValue="01/01/0001">asp:RangeValidator>


You will set the culture of current thread to the desired culture and the cast ToShortDateString will return the desired value for the prefered language.
You will set also the MinValue and the MaxValue for validator.

CultureInfo currentCultureThread = Thread.CurrentThread.CurrentCulture;
               
Thread.CurrentThread.CurrentCulture=  new CultureInfo(CurrentUser.Culture, false);

rvdate.MinimumValue = DateTime.MinValue.ToShortDateString();
rvdate.MaximumValue = DateTime.MaxValue.ToShortDateString();