Click here to Skip to main content
15,896,726 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am creating class to inherit TextBox for Date.

Onlostfocus i want to check if text entered is valid date.

How to validate date in C#.

Thanks

What I have tried:

protected override void OnLostFocus(EventArgs e)
       {
           base.OnLostFocus(e);

           if (this.Text = DateTime)

           {

           }
           else
           {
               MessageBox.Show("Invalid Date");
           }

       }
Posted
Updated 13-Mar-20 12:26pm

1 solution

DateTime.TryParse Method (System) | Microsoft Docs[^]

This method is perfect to know whether a string is a valid datetime representation.
C#
protected override void OnLostFocus(EventArgs e)
{
   base.OnLostFocus(e);

   if (DateTime.TryParse(Text, out DateTime theDate))
   {
      // ...
   }
   else
   {
      MessageBox.Show("Invalid Date");
   }
}

As a side note: why not using a DateTimePicker instead, which is the control specifically designed to input and display datetime values?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900