akosch
akosch

Reputation: 4406

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?

Upvotes: 1

Views: 9371

Answers (4)

Fandango68
Fandango68

Reputation: 4898

  protected void txtTo_TextChanged(object sender, EventArgs e)
    {
        TextBox tbTo = (TextBox)sender;
        DateTime wsToOUT;
        if (DateTime.TryParse(tbTo.Text, out wsToOUT))
        {
            //do something with valid date in tbTo
        }
        else
        {
            //show a nice error message
            tbTo.Focus();
        }
    }

Upvotes: 0

RSolberg
RSolberg

Reputation: 26982

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>

Upvotes: 2

M4N
M4N

Reputation: 96626

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

Upvotes: 2

BoltBait
BoltBait

Reputation: 11489

You could do additional validation using...

DateTime.TryParse();

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

Hope this helps.

Upvotes: 12

Related Questions