@@ -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
+ .. configuration-block ::
19
18
20
- use Symfony\Component\Validator\Constraint;
19
+ .. code-block :: php-annotations
21
20
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
- }
21
+ // src/Validator/ContainsAlphanumeric.php
22
+ namespace App\Validator;
23
+
24
+ use Symfony\Component\Validator\Constraint;
25
+
26
+ /**
27
+ * @Annotation
28
+ */
29
+ class ContainsAlphanumeric extends Constraint
30
+ {
31
+ public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
32
+ }
33
+
34
+ .. code-block :: php-attributes
35
+
36
+ // src/Validator/ContainsAlphanumeric.php
37
+ namespace App\Validator;
38
+
39
+ use Symfony\Component\Validator\Constraint;
40
+
41
+ #[\Attribute]
42
+ class ContainsAlphanumeric extends Constraint
43
+ {
44
+ public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
45
+ }
46
+
47
+ .. versionadded :: 5.2
48
+
49
+ The ability to use PHP attributes to configure constraints was introduced in
50
+ Symfony 5.2. Prior to this, Doctrine Annotations were the only way to
51
+ annotate constraints.
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