Skip to content

Commit 8939730

Browse files
committed
[Validator] Showcase custom validator constraint required option
1 parent 22da5a1 commit 8939730

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

validation/custom_constraint.rst

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,35 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen
3030
{
3131
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
3232
public $mode = 'strict'; // If the constraint has configuration options, define them as public properties
33+
34+
public function getRequiredOptions(): array
35+
{
36+
return ['mode'];
37+
}
3338
}
3439
3540
.. code-block:: php-attributes
3641
3742
// src/Validator/ContainsAlphanumeric.php
3843
namespace App\Validator;
3944
45+
use Symfony\Component\Validator\Attribute\HasNamedArguments;
4046
use Symfony\Component\Validator\Constraint;
4147
4248
#[\Attribute]
4349
class ContainsAlphanumeric extends Constraint
4450
{
4551
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
52+
53+
public string $mode;
54+
55+
#[HasNamedArguments]
56+
public function __construct(string $mode, array $groups = null, mixed $payload = null)
57+
{
58+
parent::__construct([], $groups, $payload);
59+
60+
$this->mode = $mode;
61+
}
4662
}
4763
4864
Add ``@Annotation`` or ``#[\Attribute]`` to the constraint class if you want to
@@ -271,7 +287,7 @@ not to the property:
271287
namespace App\Entity;
272288
273289
use App\Validator as AcmeAssert;
274-
290+
275291
/**
276292
* @AcmeAssert\ProtocolClass
277293
*/

0 commit comments

Comments
 (0)