Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Validation
  4. How to Validate Raw Values (Scalar Values and Arrays)
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

How to Validate Raw Values (Scalar Values and Arrays)

Edit this page

Warning: You are browsing the documentation for Symfony 3.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable 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. 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
    $errors = $validator->validate(
        $email,
        $emailConstraint
    );

    if (0 === count($errors)) {
        // ... this IS a valid email address, do something
    } else {
        // this is *not* a valid email address
        $errorMessage = $errors[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.

Validation of arrays is possible using the Collection constraint:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidator();

$input = [
    'name' => [
        'first_name' => 'Fabien',
        'last_name' => 'Potencier',
    ],
    'email' => 'test@email.tld',
    'simple' => 'hello',
    'eye_color' => 3,
    'file' => null,
    'password' => 'test',
    'tags' => [
        [
            'slug' => 'symfony_doc',
            'label' => 'symfony doc',
        ],
    ],
];

$groups = new Assert\GroupSequence(['Default', 'custom']);

$constraint = new Assert\Collection([
    // the keys correspond to the keys in the input array
    'name' => new Assert\Collection([
        'first_name' => new Assert\Length(['min' => 101]),
        'last_name' => new Assert\Length(['min' => 1]),
    ]),
    'email' => new Assert\Email(),
    'simple' => new Assert\Length(['min' => 102]),
    'eye_color' => new Assert\Choice([3, 4]),
    'file' => new Assert\File(),
    'password' => new Assert\Length(['min' => 60]),
    'tags' => new Assert\Optional([
        new Assert\Type('array'),
        new Assert\Count(['min' => 1]),
        new Assert\All([
            new Assert\Collection([
                'slug' => [
                    new Assert\NotBlank(),
                    new Assert\Type(['type' => 'string'])
                ],
                'label' => [
                    new Assert\NotBlank(),
                ],
            ]),
            new CustomUniqueTagValidator(['groups' => 'custom']),
        ]),
    ]),
]);

$violations = $validator->validate($input, $constraint, $groups);

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.
TOC
    Version
    We stand with Ukraine.
    Version:
    Be safe against critical risks to your projects and businesses

    Be safe against critical risks to your projects and businesses

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Koen Kuipers, a Symfony contributor

    Thanks Koen Kuipers (@koku) for being a Symfony contributor

    2 commits • 3 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia