Anjitha
Anjitha

Reputation: 85

Validating a date format string in c#

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

Upvotes: 1

Views: 2063

Answers (2)

sam
sam

Reputation: 969

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

Upvotes: 0

Prajwal
Prajwal

Reputation: 4000

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.

Upvotes: 1

Related Questions