You are here: Re: Best way to validate a date « PHP « IT news, forums, messages
Re: Best way to validate a date

Posted by Jamie Alessio on 09/27/03 11:10

>> I'm looking to validate a date submitted through a
>> form and I cannot decide which would be the best way
>> to do it. The form of the date needs to be:
>> YYYY-MM-DD.
>> At the moment I'm torn between using a regex,
>> something like: 20[\d][\d]-[0-1][\d]-[0-3][\d]
>> or using the checkdate() function.
>>
>> Does anyone have any pros and/or cons to implement one
>> method over the other or other methods you may have
>> used?
>>
>> Thanks,
>> David
>
>
> Better use checkdate, since it checks if the date really exists (not
> just well formatted).
> Mabye do something like this:
>
> list($check_year,$check_month,$check_day) = explode("-",$date);
> if (checkdate($check_month,$check_day,$check_year))
> echo "Date is valid";
> else
> echo "Date is not valid";
>
David,
Why not do both types of validation so that you can provide the user
with more informative error messages? First check to make sure the date
matches your regex and give them an error like "your date must me is
YYYY-MM-DD format" if it doesn't match. If it passes the regex check
then you can use checkdate() to make sure that it is a valid date (ie.
not February 31, 2004). If it doesn't pass that then give them an
informative message that lets them know the format was correct but that
they entered a date that cannot exist. After that you could even use
something like PEAR::Date to do additional checks to make sure the date
is in the past/future, etc and give messages based on those checks.

Finer-grain tests provide the opportunity to give better messages to the
user so that they can intelligibly fix the errors. It really drives me
crazy when I get errors that tell me something I entered is invalid but
don't specify *why* it is invalid. I know that the program knows
*exactly* what the problem is, but I'm left to guess and play the "well,
I'll see if this passes" game. Anyhow, just a suggestion to not pin
yourself down to a single type of test - check it in multiple ways and
provide feedback based on the various checks.

- Jamie

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация