[RESOLVED] [2005] validating date strings
Hi
Bit of a newbie question I'm afraid.
My application currently uses datetimepicker controls, but because these can't show blank dates when no date is present/needed, my users (bless 'em!) want to go back to a free format text field for entering dates.
Whilst I'm reluctant to do this as it's caused data problems on the old application that I am currently upgrading (they have a tendency to enter all kinds of different formats), I may well have to bow to pressure and do this. Therefore I want to be able to validate the date string they enter and only allow them to enter an agreed format i.e. dd/mm/yyyy.
I looked at the isDate function but that just checks it's a date and doesn't seem to check if it is a specific format. If they entered "January 2005" instead of "20/01/2005" would this function return false?
Before saving the date to the database, I'm casting the date text to a datetime in the SQL statement, so do I need to enforce a certain format or will just enforcing a recognised date e.g. "20/01/2005" or "20 January 2005" be enough?
Thanks!
Re: [2005] validating date strings
Casting data of unknown format in SQL statements is generally a bad idea; instead, you should pass the DateTime object as a parameter.
You can use the TryParse method to construct a DateTime object from a string.
Re: [2005] validating date strings
Thanks.
So, for example, if the user entered "January 2005" and I used TryParse on that, it would return False and I could display an error message but if they entered "20/01/2005" or "20 January 2005" it would return True and I could continue with the save? Is that right?
Re: [2005] validating date strings
Sorry, "January 2005" will result in a DateTime of 1 January 2005 0:00.
I should have suggested the TryParseExact method, which allows you to specify a date format string.
Re: [2005] validating date strings
Ah right..... That's really helpful, thanks!
Re: [RESOLVED] [2005] validating date strings
I'd suggest using a DateTimePicker with the ShowCheckBox property set to True. Unchecking the box would then indicate a null value. In .NET 1.x it was possible to rig the DTP to display no text when it was unchecked. In .NET 2.0 they've changed the way Windows messages are received by the control so that's not possible, or at least I couldn't find a way and I spent several hours on it. In .NET 2.0 you just have to settle for the text being greyed out.
Re: [RESOLVED] [2005] validating date strings
Thanks, jmcilhinney. I don't think my users would go for that though, it's the fact that the dtp has to display a date (albeit a dummy date) when date is null that they can't get on with. All a bit too confusing for them - poor loves! I don't think greying it out would appease them! Thanks anyway.