Home > DeveloperSection > Articles > Date Validation in C Sharp .NET

Date Validation in C Sharp .NET


C# C# 
Ratings:
0 Comment(s)
 4126  View(s)
Rate this:

Date Validation in C#.Net

Here I’m going to demonstrate how to validate date entered as string. All we have to do is to split the date string at’/’. The date provided should be in MM/DD/YYYY format.

Example

private void btnValidate_Click(object sender, EventArgs e)

        {

//this is store whether data is valid or not.

            bool b;

//spliting and storing in date array of string type.

            string[] date = txtDate.Text.Split('/');

//checking whether year is less than 2010 if true then other validations are //checked else value of b will be set to false.           

            if (Convert.ToInt32(date[2]) <= 2010)

            {

//passing entered date to DateTime constructor. If format is correct then the //code will execute otherwise exception will be raise and catched by catch //block which will set value of b to false

                try

                {

DateTime check = new DateTime(Convert.ToInt32(date[2]), Convert.ToInt32(date[0]), Convert.ToInt32(date[1]));                  

                    b = true;

                }

                catch

                {

                    b = false;

                }

            }

            else

                b = false;

//displaying message according to value of b.

            if (b)

                MessageBox.Show("Valid date");

            else

                MessageBox.Show("Date Invalid");

        }


Don't want to miss updates? Please click the below button!

Follow MindStick