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

Validate Integer Input

Php has an is_int() function, but it doesn't work with strings, unlike is_numeric() which will validate a numeric string. This was a big problem for me. The database required an int. My original solution was to force a numeric string to be an int with intval(), but the QA tester felt the integrity loss of data was too severe.

Finally found a solution in a php function I'd never seen before: filter_var(). This can validate a number of data types, but the important one for me was FILTER_VALIDATE_INT. So my validation function became:
if(!filter_var($_POST['input'], FILTER_VALIDATE_INT)){
echo "validation failed, input must be an integer";
}

Thursday, November 18

Datepicker with Dynamic Fields

Previously, I added rows to an input table. I realised later, the datepicker fields I added didn't work on these dynamic fields. Looking at the form details with the firefox web developer toolbar, I noticed the original datepicker fields had an id assigned to them of dp+randomnumber, but the new ones didn't.

I added a single line to my row adding function that solved this.
$('.datepicker').not('.hasDatePicker').datepicker();

Wednesday, November 17

255 varchar limit

Again, I have to use an MSSql database with php. I was having a problem: I'd insert a large amount of text into a varchar(1000) field, but when I tried to display it, only 255 characters came out. The problem has something to do with the drivers linux uses for php to connect to MSSql. There were two ways to handle this.

If I didn't have access to the database, I can cast the data as a text.
SELECT CAST(details as TEXT) from table
But since I had access to the database, I just changed the datatype of that field to text. Now all 1000 (even up to 2^31-1) characters will display.