Skip to content

Commit 7e1d33d

Browse files
committed
minor symfony#15618 [Validator] Showing how to pass options (ThomasLandauer)
This PR was merged into the 5.3 branch. Discussion ---------- [Validator] Showing how to pass options Two things are important: * It wasn't shown how to actually pass an option to the validator. * How to do it differs between Annotations and Attributes (notice the `options` keyword). Commits ------- b30bff4 Showing how to pass options
2 parents 0e020d0 + b30bff4 commit 7e1d33d

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

validation/custom_constraint.rst

+9-4
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen
2929
class ContainsAlphanumeric extends Constraint
3030
{
3131
public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
32+
public $mode = 'strict'; // If the constraint has configuration options, define them as public properties
3233
}
3334
3435
.. code-block:: php-attributes
@@ -45,8 +46,7 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen
4546
}
4647
4748
Add ``@Annotation`` or ``#[\Attribute]`` to the constraint class if you want to
48-
use it as an annotation/attribute in other classes. If the constraint has
49-
configuration options, define them as public properties on the constraint class.
49+
use it as an annotation/attribute in other classes.
5050

5151
.. versionadded:: 5.2
5252

@@ -103,6 +103,11 @@ The validator class only has one required method ``validate()``::
103103
// separate multiple types using pipes
104104
// throw new UnexpectedValueException($value, 'string|int');
105105
}
106+
107+
// access your configuration options like this:
108+
if ('strict' === $constraint->mode) {
109+
// ...
110+
}
106111

107112
if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
108113
// the argument must be a string or an object implementing __toString()
@@ -141,7 +146,7 @@ You can use custom validators like the ones provided by Symfony itself:
141146
142147
/**
143148
* @Assert\NotBlank
144-
* @AcmeAssert\ContainsAlphanumeric
149+
* @AcmeAssert\ContainsAlphanumeric(mode="loose")
145150
*/
146151
protected $name;
147152
@@ -161,7 +166,7 @@ You can use custom validators like the ones provided by Symfony itself:
161166
// ...
162167
163168
#[Assert\NotBlank]
164-
#[AcmeAssert\ContainsAlphanumeric]
169+
#[AcmeAssert\ContainsAlphanumeric(options: ['mode' => 'loose'])]
165170
protected $name;
166171
167172
// ...

0 commit comments

Comments
 (0)