TechniqueUse the checkdate() function, which validates a date in the format MM/DD/YYYY: <?php list ($month, $day, $year) = explode ('/', $date); if (checkdate ($month, $day, $year)) { print "Valid Date!"; } else { print "Not Valid!"; } ?> Commentscheckdate() checks the validity of a date according to the following criteria:
This solution can also be easily implemented in PHP. Here is an example of how it might be done: <?php function is_leap_year ($year) { return ((($year%4) == 0 && ($year%100)!=0) ($year%400)==0); } function is_valid_date ($date) { /* Split the date into component parts. */ list($month, $day, $year) = explode('/', $date); $month_days = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); if ($month < 1 $month > 12) return false; /* Year has to consist of 4 digits. */ if ((strlen($year) != 4) eregi("[^0-9]", $year)) return false; /* If it's a leap year, February will have 29 days. */ if (is_leap_year($year)) $month_days[1] = 29; if ($day < 1 $day > $month_days[$month - 1]) return false; return true; } ?> The previous example first splits the date by "/" and assigns the returned array to $month , $day , and $year . Then it simply tests whether each date part is within the specified range. This function also uses a little trick; $day is a string, but when it's compared against numbers , it is automatically converted to a number. So, if $day is not a numerical string, the result of the conversion will be , which is outside the specified range. |