Link to home
Start Free TrialLog in
Avatar of Sharalynn
SharalynnFlag for United States of America

asked on

Validation of string date format dd/mm/yyyy

I searched and I found a few regex solution, but is there an alternative 'normal' way of doing that?

Basically need to validate if it is a valid xx/xx/xxxx, month date (jan 31 days april 30days) and if its a leap year or no (for feb 28or29days).
Avatar of pssandhu
pssandhu
Flag of Canada image

This should help you out:
Link: http://www.dotnetspider.com/kb/Article341.aspx

P.
Avatar of Sharalynn

ASKER

Thanks, however I have the same problem as the guy over there as the code does not work. It just create the day, month, year perfectly even with 1/1/1. It does not throw any exception. Big problem!
ASKER CERTIFIED SOLUTION
Avatar of PaulHews
PaulHews
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Joel Coehoorn
Do you really need to be so specific on the date format you accept?
DateTime.TryParse() will tell you whether any string can be converted into a valid DateTime, and if you need to spit it back out in a specific format it's easy enough to then use the correct format string with the resulting DateTime object:

Dim input As String = GetDateTimeFromUser() 'imaginary function to get input
DateTime result;
If DateTime.TryParse(input, result) Then
  ' Success
Else
  Throw New Exception("Invalid DateTime")
End If
Oops:  confused some C# and VB in the same snippet.  Bad programmer, no cookie ;)
If you change the format string to dd/MM/yyyy then you will see that you get "invalid" for dates like 31/1/2007, but it will validate on 31/01/2007.  You can also specify an array of string formats if you wish to support more than one.  
>Do you really need to be so specific on the date format you accept?

Well, how else do you figure out what someone means when they enter 10/11/2007.  Do they mean 11th day 10th month, or 10th month, 11th day?
>Well, how else do you figure out what someone means when they enter 10/11/2007

It uses the Culture of the current system to decide how to interpret it, though I concede this can be a problem for web apps where that information may not be available.  
I see what you mean, but either way, you still have to be specific in terms of letting the user know which format is accepted.
Thanks, very useful and rather clear. I also used "And DateTime.Today > DateString" if you want to make sure they do not enter a future date!