Skip to content

[Validator] Showcase custom validator constraint required option #16770

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 54 additions & 1 deletion validation/custom_constraint.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,59 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen
Add ``@Annotation`` or ``#[\Attribute]`` to the constraint class if you want to
use it as an annotation/attribute in other classes.

.. versionadded:: 6.1

The ``#[HasNamedArguments]`` attribute was introduced in Symfony 6.1.

You can use ``#[HasNamedArguments]`` or ``getRequiredOptions()`` to make some constraint options required:

.. configuration-block::

.. code-block:: php-annotations

// src/Validator/ContainsAlphanumeric.php
namespace App\Validator;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class ContainsAlphanumeric extends Constraint
{
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
public $mode;

public function getRequiredOptions(): array
{
return ['mode'];
}
}

.. code-block:: php-attributes

// src/Validator/ContainsAlphanumeric.php
namespace App\Validator;

use Symfony\Component\Validator\Attribute\HasNamedArguments;
use Symfony\Component\Validator\Constraint;

#[\Attribute]
class ContainsAlphanumeric extends Constraint
{
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';

public string $mode;

#[HasNamedArguments]
public function __construct(string $mode, array $groups = null, mixed $payload = null)
{
parent::__construct([], $groups, $payload);

$this->mode = $mode;
}
}

Creating the Validator itself
-----------------------------

Expand Down Expand Up @@ -271,7 +324,7 @@ not to the property:
namespace App\Entity;

use App\Validator as AcmeAssert;

/**
* @AcmeAssert\ProtocolClass
*/
Expand Down