Skip to content

Commit ebbc61d

Browse files
committed
minor #16770 [Validator] Showcase custom validator constraint required option (norkunas)
This PR was merged into the 6.1 branch. Discussion ---------- [Validator] Showcase custom validator constraint required option Closes #16674 Commits ------- dba5d2a [Validator] Showcase custom validator constraint required option
2 parents 7a24636 + dba5d2a commit ebbc61d

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

validation/custom_constraint.rst

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,59 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen
4848
Add ``@Annotation`` or ``#[\Attribute]`` to the constraint class if you want to
4949
use it as an annotation/attribute in other classes.
5050

51+
.. versionadded:: 6.1
52+
53+
The ``#[HasNamedArguments]`` attribute was introduced in Symfony 6.1.
54+
55+
You can use ``#[HasNamedArguments]`` or ``getRequiredOptions()`` to make some constraint options required:
56+
57+
.. configuration-block::
58+
59+
.. code-block:: php-annotations
60+
61+
// src/Validator/ContainsAlphanumeric.php
62+
namespace App\Validator;
63+
64+
use Symfony\Component\Validator\Constraint;
65+
66+
/**
67+
* @Annotation
68+
*/
69+
class ContainsAlphanumeric extends Constraint
70+
{
71+
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
72+
public $mode;
73+
74+
public function getRequiredOptions(): array
75+
{
76+
return ['mode'];
77+
}
78+
}
79+
80+
.. code-block:: php-attributes
81+
82+
// src/Validator/ContainsAlphanumeric.php
83+
namespace App\Validator;
84+
85+
use Symfony\Component\Validator\Attribute\HasNamedArguments;
86+
use Symfony\Component\Validator\Constraint;
87+
88+
#[\Attribute]
89+
class ContainsAlphanumeric extends Constraint
90+
{
91+
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
92+
93+
public string $mode;
94+
95+
#[HasNamedArguments]
96+
public function __construct(string $mode, array $groups = null, mixed $payload = null)
97+
{
98+
parent::__construct([], $groups, $payload);
99+
100+
$this->mode = $mode;
101+
}
102+
}
103+
51104
Creating the Validator itself
52105
-----------------------------
53106

@@ -271,7 +324,7 @@ not to the property:
271324
namespace App\Entity;
272325
273326
use App\Validator as AcmeAssert;
274-
327+
275328
/**
276329
* @AcmeAssert\ProtocolClass
277330
*/

0 commit comments

Comments
 (0)