jpl
jpl

Reputation: 205

DateTime and String Validation

I have a simple question about DateTime in c#.

I have a textbox where I ask the user to input a date.

I want to validate that the textbox is not empty before parsing the string to a datetime to validate if the date is in the right format.

Here is a bit of my code:

String strStartDate = txtStartDate.txt;

DateTime StartDate = DateTime.Parse(strStartDate);

I have other text boxes for the names and such and I also validate if they are empty with a if statement like this (same if statement to validate if strStartDate is empty):

    if (strFirstName.Trim() == "")
    {

        txtFirstName.BackColor = System.Drawing.Color.Yellow;

        errorMessage = errorMessage + "First Name may not be empty. ";
    }

    else
    {

        txtFirstName.BackColor = System.Drawing.Color.White;

    }

The debugger stops as soon as I try the submit button, it says that String was not recognized as a valid DateTime.

Is there a way to see if the string is empty before validating the DateTime?

Upvotes: 0

Views: 814

Answers (2)

Brandon Moore
Brandon Moore

Reputation: 8790

You can also use TryParse:

        string SomeDate = "1/1/2012";
        DateTime dt;
        var success = DateTime.TryParse(SomeDate, out dt);

Then you can check success to see if it was a valid date or not. This will protect you from any invalid date string, not just an empty or null string.

Upvotes: 2

parapura rajkumar
parapura rajkumar

Reputation: 24433

String.IsNullOrEmpty will do what you want

Upvotes: 0

Related Questions