How to check or check the entered date in a text field in the format DD / MM / YYYY?

How to check or check the entered date in a text box in the format DD/MM/YYYY?

+3
source share
8 answers

Markup:

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

Code for:

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 the following command:

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

Another option is to use expression validation. The regular expression below checks for DD / MM / YYYY, but of course there is no way to tell if something like 01 is DD or MM. Otherwise, this is a 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$" />
+4
source
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;
}
+1

CustomValidator, , .
13/12/2001 , 12/13/2001 .

0

, , , , DD/MM/YYYY.

DateTime dt;
if (!DateTime.TryParse(texbox.Text, new  System.Globalization.CultureInfo("en-GB"), System.Globalization.DateTimeStyles.None, dt))
{
    // text is not in the correct format
}
0

, regexvalidator ( " , " ) . CustomValidator serveride, DateTime.Parse , "29 2010".

CompareValidator , , ( - , ).

0

You can not. The user instead selects a data collector. An example is here .

-2
source

Source: https://habr.com/ru/post/1749191/


All Articles