Comic Coder
Comic Coder

Reputation: 549

How to validate string is correct date time

I have some data picked up from an excel file.

I want to validate that the user has entered a valid date time string. I have tried to use DateTime.Parse method but found that certain values seem to be accepted.

For example,

If I submit 3.3 as a date time this is accepted by the DateTime.Parse method as a valid date time and outputs 03/03/2012 00:00:00

I want to want to block this. Only allowing the user to enter correctly formatted date times.

So for example a user could supply 03/03/2012 or 03/03/2012 12:30:00 but not values like 01022012 or 3.3.2012

Any Ideas?

Upvotes: 2

Views: 2118

Answers (3)

SajjadHashmi
SajjadHashmi

Reputation: 3695

You can handle it on the client side with various jquery plugin/functions like this or a simple Google search can return many other useful results.

if you want to handle it on the server side, (I am not sure on what project you are working) but depending over it you can write your own method/use Regex or Data Annotation MVC.

If you are still having trouble try adding few details about your project such as Language, Architecture etc. that would help more in providing the right solution.

Hope it helps. Thankyou

Upvotes: 1

Paul Alan Taylor
Paul Alan Taylor

Reputation: 10680

You want to use DateTime.ParseExact or DateTime.TryParseExact

This allows you do parse from a date format string of your choice.

http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx

Examples here:-

http://msdn.microsoft.com/en-us/library/ms131044.aspx

Upvotes: 2

Martin Macak
Martin Macak

Reputation: 3821

You can use RegEx to to this. Something like this should help @"\d{2}/\d{2}/\d{4}(\s+\d{2}\:\d{2}\:\d{2})?"

Upvotes: 1

Related Questions