Skip to content

[Validator] Showing how to pass options #15618

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
Aug 13, 2021
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
13 changes: 9 additions & 4 deletions validation/custom_constraint.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen
class ContainsAlphanumeric extends Constraint
{
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
public $mode = 'strict'; // If the constraint has configuration options, define them as public properties
}

.. code-block:: php-attributes
Expand All @@ -45,8 +46,7 @@ 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. If the constraint has
configuration options, define them as public properties on the constraint class.
use it as an annotation/attribute in other classes.

.. versionadded:: 5.2

Expand Down Expand Up @@ -103,6 +103,11 @@ The validator class only has one required method ``validate()``::
// separate multiple types using pipes
// throw new UnexpectedValueException($value, 'string|int');
}

// access your configuration options like this:
if ('strict' === $constraint->mode) {
// ...
}

if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
// the argument must be a string or an object implementing __toString()
Expand Down Expand Up @@ -141,7 +146,7 @@ You can use custom validators like the ones provided by Symfony itself:

/**
* @Assert\NotBlank
* @AcmeAssert\ContainsAlphanumeric
* @AcmeAssert\ContainsAlphanumeric(mode="loose")
*/
protected $name;

Expand All @@ -161,7 +166,7 @@ You can use custom validators like the ones provided by Symfony itself:
// ...

#[Assert\NotBlank]
#[AcmeAssert\ContainsAlphanumeric]
#[AcmeAssert\ContainsAlphanumeric(options: ['mode' => 'loose'])]
protected $name;

// ...
Expand Down