1
votes

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

2
Give all the valid formats in the combo instead. Easy for user and you bothMohit Shrivastava
You can make use of regexkashi_rock
@ Mohit Shrivastava i tried it ..but it seems to be a very long listAnjitha
@kashi_rock can u explain it plsAnjitha
You will get all possible DateTime formats from Here populate those values to a ComboBox as My friend Mohit suggest. so that your users can select a format from that listsujith karivelil

2 Answers

1
votes

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.

0
votes

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