@@ -12,20 +12,43 @@ alphanumeric characters.
12
12
Creating the Constraint Class
13
13
-----------------------------
14
14
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 `:
16
16
17
- // src/Validator/ContainsAlphanumeric.php
18
- namespace App\Validator;
17
+ .. versionadded :: 5.2
19
18
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.
21
22
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
+ }
29
52
30
53
.. note ::
31
54
@@ -128,6 +151,25 @@ You can use custom validators like the ones provided by Symfony itself:
128
151
// ...
129
152
}
130
153
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
+
131
173
.. code-block :: yaml
132
174
133
175
# config/validator/validation.yaml
@@ -241,6 +283,14 @@ not to the property:
241
283
// ...
242
284
}
243
285
286
+ .. code-block :: php-attributes
287
+
288
+ #[AcmeAssert\ProtocolClass]
289
+ class AcmeEntity
290
+ {
291
+ // ...
292
+ }
293
+
244
294
.. code-block :: yaml
245
295
246
296
# config/validator/validation.yaml
0 commit comments