How to inject validator in Symfony

To do this, your custom class will need to be defined as a service, and you'll access it from the controller using $form = $this->get('your.form.service'); instead of instantiating it directly.

When defining your service, make sure to inject the validator service:

your.form.service:
    class: Path\To\Your\Form
    arguments: [@validator]

Then you'll need to handle this in the construct method of your Form service:

/**
 * @var \Symfony\Component\Validator\Validator
 */
protected $validator;

function __construct(\Symfony\Component\Validator\Validator $validator)
{
    $this->validator = $validator;
}

In Symfony 4+, if you use the default configuration (with auto wiring enabled), the easiest way is to inject a ValidatorInterface.

For instance:

<?php

use Symfony\Component\Validator\Validator\ValidatorInterface;

class MySuperClass
{
    private $validator;

    public function __construct(
        ValidatorInterface $validator
    ) {
        $this->validator = $validator;
    }

From Symfony2.5 on

Validator is called RecursiveValidator so, for injection

use Symfony\Component\Validator\Validator\RecursiveValidator;
function __construct(RecursiveValidator $validator)
{
    $this->validator = $validator;
}