I recently needed a library for validating form input and everything seemed either verbose or required a huge number of files and libraries to be included. Here’s what I was looking for:

  • Easy to include in projects without having to change include paths, mess with auto loaders, or include other frameworks
  • Something that minimized the amount of validation code that needed to be written, preferably with a fluent interface
  • Ability to generate error messages that can be shown to the end user
  • Ability to transform data to data types needed by the rest of the script
  • Capability to validate against arbitrary regexes
  • Capability to validate against closures or other external functions

I couldn’t find exactly what I was looking for, so I decided to write it myself. I added the result, InputValidator, to my gUtils collection of PHP classes on Github. InputValidator is a standalone script for validating user input from forms or other sources.

Everything is in a single file, making it easy to include in any (PHP 5.3+) project. Here’s some example usage:

<?
require('gUtils/InputValidator.php');
// this could be from $_POST
$data = array(
  'name' => 'Greg Neustaetter',
  'email' => 'greg@emailaddress.com',
  'website' => 'http://www.gregphoto.net',
  'favoriteNumber' => 'xyz',
  'date' => '11/11/2011'
);
 
// pass in the data to be validated
$v = new gUtils\InputValidator($data);
 
// validate each field
$v->field('name')->required()->length(3,50);
$v->field('email', 'Email Address')->required()->email();
$v->field('website')->url();
$v->field('favoriteNumber', 'Your favorite number')->intRange(0,100)->toInt();
$v->field('date')->toDateTime('m/d/Y')->after(time()); // after the current time
 
if(!$v->allValid()) {
    echo '<pre>';
    print_r($v->getErrors()); // returns an array of errors indexed by field
    echo '<pre>';
    exit();
} 
$data = $v->getValues();  // returns an array of values indexed by field
$name = $v->get('name'); // get the value of name
echo $v->escape('name'); // escape the value of name for output with htmlspecialchars

This script would print the following error array:

Array(
    'favoriteNumber' => Your favorite number must be an integer between 0 and 100
    'date' => Date cannot be before 12/24/2011
)

In addition to validation the library includes a few filters to manipulate data and cast it to formats needed by your code. Take a look at the documentation on the Github wiki for a list of the 20 validators and the 8 filters.

Let me know if you find it useful or if you have any feedback…