1

I want users to be able to enter a date format string in a text box so they can specify how they want a date value to be Displayed in their windows form

How can I validate this date format string entered in a text box so that they can enter only a valid C# Date format

Anjitha
  • 85
  • 1
  • 8

2 Answers2

1

For a valid date, you need date (dd), month (mm) and year(yyyy). I can give you a simple regex, for validating dates like dd/mm/yy or dd.mm/yyyy

(dd|mm|yy{2,4}?).(dd|mm||yy{2,4}?).(dd|mm||yy{2,4}?)

It passes for any combination of dd,mm and yyyy or yy.

It also accepts dd.dd.mm or anything like that. So, Make sure you check for multiple occurrences of characters.

Prajwal
  • 3,930
  • 5
  • 24
  • 50
0

You can use DateTime.TryParse and check whether the entered date time string is valid or not.

Here is the code:

DateTime dt;
string myDate = "2016-12-10";
bool success = DateTime.TryParse(myDate, out dt);
Console.WriteLine(success);

Console.WriteLine(DateTime.TryParse("2016-12-10", out dt));    //true
Console.WriteLine(DateTime.TryParse("10-12-2016", out dt));    //true
Console.WriteLine(DateTime.TryParse("2016 July, 01", out dt));    //true
Console.WriteLine(DateTime.TryParse("July 2016 99", out dt));    //true
sam
  • 931
  • 2
  • 13
  • 26
  • This addresses the question of validating a user-supplied _date_ but not a user-supplied date _format_. – JYelton Feb 28 '17 at 18:24