How to Validate Raw Values (Scalar Values and Arrays)

3.3 version

How to Validate Raw Values (Scalar Values and Arrays)

Usually you will be validating entire objects. But sometimes, you just want to validate a simple value - like to verify that a string is a valid email address. This is actually pretty easy to do. From inside a controller, it looks like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ...
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validator\ValidatorInterface;

// ...
public function addEmailAction($email, ValidatorInterface $validator)
{
    $emailConstraint = new Assert\Email();
    // all constraint "options" can be set this way
    $emailConstraint->message = 'Invalid email address';

    // use the validator to validate the value
    $errorList = $validator->validate(
        $email,
        $emailConstraint
    );

    if (0 === count($errorList)) {
        // ... this IS a valid email address, do something
    } else {
        // this is *not* a valid email address
        $errorMessage = $errorList[0]->getMessage();

        // ... do something with the error
    }

    // ...
}

By calling validate on the validator, you can pass in a raw value and the constraint object that you want to validate that value against. A full list of the available constraints - as well as the full class name for each constraint - is available in the constraints reference section.

The validate() method returns a ConstraintViolationList object, which acts just like an array of errors. Each error in the collection is a ConstraintViolation object, which holds the error message on its getMessage() method.


This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.