i want a regular expression to validate date of the kind "13/08/2010" how to make it?
Regular expression for dd/MM/yyyy. it will also support leap year...
^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$
Or you can also use CompareValidator with Type="Date"
<asp:TextBox runat="server" ID="txtDate" />
<asp:CustomValidator runat="server" ControlToValidate="txtDate" ErrorMessage="Error" OnServerValidate="customValidator_ServerValidate" />
protected void customValidator_ServerValidate(object sender, ServerValidateEventArgs e)
{
DateTime d;
e.IsValid = DateTime.TryParse(
e.Value,
System.Globalization.CultureInfo.InvariantCulture,
"dd/MM/yyyy",
out d);
// or if you want to try all available formats, not only the specific one
e.IsValid = DateTime.TryParse(
e.Value,
out d);
}
See MSDN:
Using regular expressions is probably the wrong thing to do here. What you really want from your users is a valid date, right? But you have to take into account localisation and the fact that dates are represented differently in different cultures. If someone from the US was using your app they probably can't understand why 01/23/2010 is not a valid date, when to them it is.
Instead, you should using the compare validator setting the Operator property to 'DataTypeCheck
'. This allows users to enter dates in whatever format they are familiar with and you can still validate they are a date. An example:
<asp:CompareValidator id="DateCompareValidator" runat="server"
Type="Date" Operator="DataTypeCheck" ControlToValidate="TextboxDate"
ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>