Tuesday, November 30

Valid Dates

OMG, two in one day!

A user uses the datepicker to enter a date, but it's still a text field, they could type in some nonexistent date. JQuery validation checks to make sure it's a correct date format, but not whether it's a valid date. ie: 30/30/2009 is a valid date.

Php checkdate() will make sure it's a valid date. Easy if your date comes in in separate variables, but mine came in from datepicker or from the database, so it looks like either 11/30/2010 or Nov 30, 2010.

So first of all, if the date comes in from the database, I make sure to format it before I echo it. I could do this with the sql query, but it's long and I don't want to. So I do:
if($row['indate'] == "Jan 01 1900 12:00AM") echo "";
else echo date("n/d/Y", strtotime($row['indate']));
This also takes care of MSSql's default dates, we just don't want those to show up at all.
Then when submitting the form, the validation is:
if($_POST['indate'] <> ''){  
   $arr=split("/",$_POST['indate']);
   $mm=$arr[0];
   $dd=$arr[1];
   $yy=$arr[2];
   if(!checkdate($mm,$dd,$yy)){
     $errormsg = 'Input is an invalid date: '.$_POST['indate'];
   }
}

References:
php.net
plus2net.com

No comments: