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 DateTimeconstructor. 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");
        }


 

 

Leave Comment