Monday, April 11, 2011

What is the simplest way to validate a date in asp.net C#?

I'm using DateTime.ParseExact to parse a string from input. What is the simplest way to make sure the date complies to rules like max days in a month or no 0. month?

From stackoverflow
  • You could do additional validation using...

    DateTime.TryParse();
    

    http://msdn.microsoft.com/en-us/library/9h21f14e.aspx

    Hope this helps.

  • As BoltBait said, or DateTime.TryParseExact() if you know the exact format of the string.

    http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx

  • The answers for doing the DateTime.TryParse() are great if you are doing this check in your code behind, but if you are capturing this data on the UI, then I would highly reccomend validing the input as well before the postback to the code behind occurs.

    <strong>Date:</strong>
    <asp:textbox ID="txtEnterDate" runat="server"></asp:textbox>
    <asp:CompareValidator ID="cvEnterDate" runat="server" ControlToValidate="txtEnterDate"
        ErrorMessage="Must Be Valid Date" Operator="DataTypeCheck" 
        SetFocusOnError="True" Type="Date"></asp:CompareValidator>
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.