Skip to content

Metadata

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

Read the updated version of this page for Symfony 7.2 (the current stable version).

The ClassMetadata class represents and manages all the configured constraints on a given class.

Properties

The Validator component can validate public, protected or private properties. The following example shows how to validate that the $firstName property of the Author class has at least 3 characters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ...
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    private $firstName;

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('firstName', new Assert\NotBlank());
        $metadata->addPropertyConstraint(
            'firstName',
            new Assert\Length(["min" => 3])
        );
    }
}

Getters

Constraints can also be applied to the value returned by any public getter method, which are the methods whose names start with get, has or is. This feature allows to validate your objects dynamically.

Suppose that, for security reasons, you want to validate that a password field doesn't match the first name of the user. First, create a public method called isPasswordSafe() to define this custom validation logic:

1
2
3
4
public function isPasswordSafe()
{
    return $this->firstName !== $this->password;
}

Then, add the Validator component configuration to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
// ...
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([
            'message' => 'The password cannot match your first name',
        ]));
    }
}

Classes

Some constraints allow to validate the entire object. For example, the Callback constraint is a generic constraint that's applied to the class itself.

Suppose that the class defines a validate() method to hold its custom validation logic:

1
2
3
4
5
6
7
// ...
use Symfony\Component\Validator\Context\ExecutionContextInterface;

public function validate(ExecutionContextInterface $context)
{
    // ...
}

Then, add the Validator component configuration to the class:

1
2
3
4
5
6
7
8
9
10
11
// ...
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addConstraint(new Assert\Callback('validate'));
    }
}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version