Using the Symfony Validator as a standalone component

symfony_logo_250pxIt’s easy to think of Symfony as just being a huge full-stack PHP framework, that you either base your entire project around or ignore completely, but in fact, the individual Symfony components can be surprisingly easy to slot into an existing project. This is just a quick post to show how to use the Symfony Validator component outside of the full Symfony framework to validate objects, and without having to use annotations to define the validation constraints.

(Because, at the time of writing, the docs don’t explain it very well, and you may not want to install Doctrine just for annotation support.)

Assuming you’ve already configured your composer.json and got the Validator component somewhere PHP can find it, the class to be validated should look something like the User class shown below. Here we just want to validate that a User has a name and that it is of an acceptable length.

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
class User
private $name;
public function __construct($name)
$this->name = $name;
* This method is where you define your validation rules.
public static function loadValidatorMetadata(ClassMetadata $metadata)
// A user must have a name
$metadata->addPropertyConstraint('name', new Assert\NotBlank());
// And a valid name is 5-50 characters long
$metadata->addPropertyConstraint('name', new Assert\Length(
array('min' => 5, 'max' => 50)
// Add more rules here as needed.

And then to validate an instance of User, you can do something like this. It’s important to note here that you must call ‘addMethodMapping’ on the ValidatorBuilder, or your object will not be validated against the rules you have defined (and you will tear your hair out wondering why not).

use Symfony\Component\Validator\Validation;
$user = new User('my_test_user');
$validator = Validation::createValidatorBuilder()
$violations = $validator->validate($user);
if (count($violations) > 0) {
// $user was invalid :(
// Yay! $user was valid
This entry was posted in PHP and tagged , , . Bookmark the permalink.