Skip to content

Commit 2f2736b

Browse files
committed
Use PHP attributes when creating custom validation constraints
1 parent 2fe9150 commit 2f2736b

File tree

1 file changed

+55
-11
lines changed

1 file changed

+55
-11
lines changed

validation/custom_constraint.rst

Lines changed: 55 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,37 @@ 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+
.. configuration-block::
1918

20-
use Symfony\Component\Validator\Constraint;
19+
.. code-block:: php-annotations
2120
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+
}
2946
3047
.. note::
3148

@@ -128,6 +145,25 @@ You can use custom validators like the ones provided by Symfony itself:
128145
// ...
129146
}
130147
148+
.. code-block:: php-attributes
149+
150+
// src/Entity/AcmeEntity.php
151+
namespace App\Entity;
152+
153+
use App\Validator as AcmeAssert;
154+
use Symfony\Component\Validator\Constraints as Assert;
155+
156+
class AcmeEntity
157+
{
158+
// ...
159+
160+
#[Assert\NotBlank()]
161+
#[AcmeAssert\ContainsAlphanumeric()]
162+
protected $name;
163+
164+
// ...
165+
}
166+
131167
.. code-block:: yaml
132168
133169
# config/validator/validation.yaml
@@ -241,6 +277,14 @@ not to the property:
241277
// ...
242278
}
243279
280+
.. code-block:: php-attributes
281+
282+
#[AcmeAssert\ProtocolClass()]
283+
class AcmeEntity
284+
{
285+
// ...
286+
}
287+
244288
.. code-block:: yaml
245289
246290
# config/validator/validation.yaml

0 commit comments

Comments
 (0)