C# Regular Expression to validate a date?

后端 未结 10 1656
后悔当初
后悔当初 2020-12-30 04:45

I am trying to validate a date entered into a text box. There is an input mask on the textbox which forces input of xx/xx/xxxx. I am trying to use a regular expression valid

相关标签:
10条回答
  • 2020-12-30 05:23

    As an alternative, you can use CompareValidator instead of RegularExpressionValidator. It goes like this:

    <asp:CompareValidator ID="CompareValidator2" runat="server" ControlToValidate="txtIssueDate" ErrorMessage="Invalid Date Format" Type="Date" Operator="DataTypeCheck" Display="Dynamic" Text="*" ForeColor="Red" ValidationGroup="valGroup1"></asp:CompareValidator>

    0 讨论(0)
  • 2020-12-30 05:27

    The above regular expression is correct for dd/mm/yyyy format. the expression is

    (^((((0[1-9])|([1-2][0-9])|(3[0-1]))|([1-9]))\x2F(((0[1-9])|(1[0-2]))|([1-9]))\x2F(([0-9]{2})|(((19)|([2]([0]{1})))([0-9]{2}))))$)
    
    0 讨论(0)
  • 2020-12-30 05:29

    Last answer is actually the correct way to do. Use DateTime.TryParse.

    Example:

    DateTime dt;
    if(DateTime.TryParse(Textbox1.Text,out dt))
    {
     Label1.Text = "Invalid date format";
    }
    
    0 讨论(0)
  • 2020-12-30 05:31
    ([0][1-9]|[1][0-9|][2][0-9]|[3][0-1])\/([0][1-9]|[1][0-2])\/[1-2][0-9][0-9][0-9]
    

    for dd/mm/yyyy (year can be from 1000 to 2999)

    or

    (([0][1-9]|[2][0-9]|[3][0-1]|[1-9]|[1][0-9])/([0][1-9]|[1][0-2]|[1-9])/([1-2][0-9][0-9][0-9]|[0-9][0-9]))

    which includes d/m/yy (e.g. 1/12/82)

    0 讨论(0)
  • 2020-12-30 05:33

    Why not use one of the methods available in the System.DateTime namespace? You could use DateTime.TryParse() (edit: DateTime.TryParseExact() is probably the right suggestion) to accomplish the validation.

    0 讨论(0)
  • 2020-12-30 05:38

    You can use DateTime.TryParseExact:

    DateTime dt;
    
    bool isValid = DateTime.TryParseExact(
        "08/30/2009",
        "MM/dd/yyyy",
        CultureInfo.InvariantCulture,
        DateTimeStyles.None,
        out dt);
    
    0 讨论(0)
提交回复
热议问题