How to check or validate the textbox entered date is in DD/MM/YYYY format?

73,879

Solution 1

Markup:

<asp:Textbox runat="server" ID="TextBox1" />
<asp:CustomValidator runat="server" ControlToValidate="TextBox1" ErrorMessage="Date was in incorrect format" OnServerValidate="CustomValidator1_ServerValidate" />

Code-behind:

protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
    DateTime d;
    e.IsValid = DateTime.TryParseExact(e.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
}

if you want to allow several formats and only them, use next:

DateTime.TryParseExact(e.Value, new[] { "dd/MM/yyyy", "yyyy-MM-dd" }, CultureInfo.InvarinatCulture, DateTimeStyles.None, out d);

Solution 2

Another option is using a regular expression validator. The regular expression below checks for DD/MM/YYYY but of course there is no way to distinguish if something like 01 is DD or MM. Otherwise it does the trick.

<asp:TextBox ID="txtDate" runat="server"/>
<asp:RegularExpressionValidator ID="regexpName" runat="server"     
                                ErrorMessage="This expression does not validate." 
                                ControlToValidate="txtDate"     
                                ValidationExpression="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$" />

Solution 3

DateTime Result;
DateTimeFormatInfo info = new DateTimeFormatInfo ( );
CultureInfo culture;
culture = CultureInfo.CreateSpecificCulture ( "en-US" );
info.ShortDatePattern = "dd/MM/yyyy";
if ( DateTime.TryParse ( StrDate, info, DateTimeStyles.None, out Result ) )
{
  return StrDate;
}
Share:
73,879
Innova
Author by

Innova

im very straight forward person

Updated on July 16, 2022

Comments

  • Innova
    Innova almost 2 years

    How to check or validate the textbox entered date is in DD/MM/YYYY format?