I am creating an calendar control using ajax calendar extender.In that control i need to validate date from and to.For that i use asp RangeValidator control.Calander formate is set to [MM/dd/yyyy].

<asp:RangeValidator ID="RGvDt" runat="server" ErrorMessage="Invalid Date" 
        ForeColor="Red" Display="Dynamic" ControlToValidate="txtDate" Type="Date">
</asp:RangeValidator> 

But it is not working.It allays troughs error

The value '01/31/2022' of the MaximumValue property of 'RGvDt' cannot be converted to type 'Date'.

But this code works fine in aspx page.Can any one tell me how can i use RangeValidator into my user control.And how can i change validation format to [dd/MM/yyyy]

有帮助吗?

解决方案

The / has a special meaning in a date format string. It means: "replace me with your curent culture's date separator". In germany for example it is ..

MSDN

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfoDateSeparator property of the current or specified culture. ...

I think the only way is using a CustomValidator to check this format. Then you can parse the date in this way(on serverside):

DateTime dt;
if(DateTime.TryParseExact(txtDate, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    // now there is a valid date in dt
}

Notice the CultureInfo.InvariantCulture which i have used to enforce the / as actual date separator.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top