Skip to content

Commit 7212a90

Browse files
committed
Use PHP attributes when creating custom validation constraints
1 parent 1e1f012 commit 7212a90

File tree

1 file changed

+61
-11
lines changed

1 file changed

+61
-11
lines changed

validation/custom_constraint.rst

Lines changed: 61 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,43 @@ alphanumeric characters.
1212
Creating the Constraint Class
1313
-----------------------------
1414

15-
First you need to create a Constraint class and extend :class:`Symfony\\Component\\Validator\\Constraint`::
15+
First you need to create a Constraint class and extend :class:`Symfony\\Component\\Validator\\Constraint`:
1616

17-
// src/Validator/ContainsAlphanumeric.php
18-
namespace App\Validator;
17+
.. versionadded:: 5.2
1918

20-
use Symfony\Component\Validator\Constraint;
19+
The ability to use PHP attributes to configure constraint was introduced in
20+
Symfony 5.2. Prior to this, Doctrine Annotations were the only way to
21+
annotate constraints.
2122

22-
/**
23-
* @Annotation
24-
*/
25-
class ContainsAlphanumeric extends Constraint
26-
{
27-
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
28-
}
23+
.. configuration-block::
24+
25+
.. code-block:: php-annotations
26+
27+
// src/Validator/ContainsAlphanumeric.php
28+
namespace App\Validator;
29+
30+
use Symfony\Component\Validator\Constraint;
31+
32+
/**
33+
* @Annotation
34+
*/
35+
class ContainsAlphanumeric extends Constraint
36+
{
37+
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
38+
}
39+
40+
.. code-block:: php-attributes
41+
42+
// src/Validator/ContainsAlphanumeric.php
43+
namespace App\Validator;
44+
45+
use Symfony\Component\Validator\Constraint;
46+
47+
#[\Attribute]
48+
class ContainsAlphanumeric extends Constraint
49+
{
50+
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
51+
}
2952
3053
.. note::
3154

@@ -128,6 +151,25 @@ You can use custom validators like the ones provided by Symfony itself:
128151
// ...
129152
}
130153
154+
.. code-block:: php-attributes
155+
156+
// src/Entity/AcmeEntity.php
157+
namespace App\Entity;
158+
159+
use App\Validator as AcmeAssert;
160+
use Symfony\Component\Validator\Constraints as Assert;
161+
162+
class AcmeEntity
163+
{
164+
// ...
165+
166+
#[Assert\NotBlank]
167+
#[AcmeAssert\ContainsAlphanumeric]
168+
protected $name;
169+
170+
// ...
171+
}
172+
131173
.. code-block:: yaml
132174
133175
# config/validator/validation.yaml
@@ -241,6 +283,14 @@ not to the property:
241283
// ...
242284
}
243285
286+
.. code-block:: php-attributes
287+
288+
#[AcmeAssert\ProtocolClass]
289+
class AcmeEntity
290+
{
291+
// ...
292+
}
293+
244294
.. code-block:: yaml
245295
246296
# config/validator/validation.yaml

0 commit comments

Comments
 (0)