Posted on Jan 02, 2014 By Philip Whitt

Web application security is an important and often overlooked aspect of development. At the core of security is validation and sanitizing user input. There are many different ways to validate user input in PHP. My approach is a simple builder object that allows a developer to chain together common validators for an easy to read list of validation rules. 

A Simple Validation Example
<?php

use Core\Validator as val;
try {
    $name = new val\Builder('Philip Whitt');
    $name->notEmpty()->isOnlyAlpha()->hasLengthGt(2)->get();

} catch (val\EmptyValueException $e) {
    // Handle empty value error
} catch (val\AlphaException $e) {
    // Handle non alpha error
} catch (val\InvalidLengthException $e) {
    // Handle length error
} catch (val\Exception $e) {     // Handle generic validation error }
In the example above, it is clear that the $name variable must not be empty, only letters and have a length greater than 2 characters.

Validate User Input
<?php

use Core\Validator as val;

$validator = new val\ParamFactory($_REQUEST);

// Validate "id"
try {
    $id = $validator->getVar('id')->notEmpty()->isOnlyNum()->get();
} catch (val\Exception $e) {
    // Handle generic id error
}

// Validate "name"
try {
    $name = $validator->getVar('name')->notEmpty()->isOnlyAlpha()->hasLengthGt(2)->get();
} catch (val\Exception $e) {
    // Handle generic name error
}
The ParamFactory is a wrapper for associative arrays. It just so happens that $_POST/GET are associative arrays so you can access their keys via the ParamFactory that then returns a Builder object with the value.

Install via Composer
Composer is a great way to manage third party PHP packages. Assuming you're using the composer autoloader and/or conforming to PSR-0 standards, you can simple add the dependancies below to your composer.json and start using the validators.
{
"require": {
"php" : ">=5.3",
"core/validator" : "dev-master"
}
}

Checkout more examples plus comprehensive unit tests at https://github.com/philipwhitt/core-validator



Back to Blog