Tuesday, November 30

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";
}

No comments: