Re: Best way to validate a date

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux