Skip to content

Commit abfd38e

Browse files
committed
minor symfony#7805 [Validator] Added array validation example to raw values (CoolGoose, javiereguiluz, wouterj)
This PR was merged into the 2.7 branch. Discussion ---------- [Validator] Added array validation example to raw values This example was removed from the component's README and it has some value imo. Finishes symfony#7161 Commits ------- 06f67b4 Moved array validation to the Raw values sub-guide 64f5ad9 Fixed some syntax issues c8b6b45 missing constraint example from the old readme
2 parents 0dbeb2c + 06f67b4 commit abfd38e

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

components/validator.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ characters long::
4646
}
4747
}
4848

49+
The validator returns the list of violations.
50+
4951
Retrieving a Validator Instance
5052
-------------------------------
5153

validation/raw_values.rst

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,34 @@ looks like this::
4646
// ...
4747
}
4848

49-
By calling ``validate`` on the validator, you can pass in a raw value and
49+
By calling ``validate()`` on the validator, you can pass in a raw value and
5050
the constraint object that you want to validate that value against. A full
5151
list of the available constraints - as well as the full class name for each
5252
constraint - is available in the :doc:`constraints reference </reference/constraints>`
5353
section.
5454

55+
Validation of arrays is possible using the ``Collection`` constraint::
56+
57+
use Symfony\Component\Validator\Validation;
58+
use Symfony\Component\Validator\Constraints as Assert;
59+
60+
$validator = Validation::createValidator();
61+
62+
$constraint = new Assert\Collection(array(
63+
// the keys correspond to the keys in the input array
64+
'name' => new Assert\Collection(array(
65+
'first_name' => new Assert\Length(array('min' => 101)),
66+
'last_name' => new Assert\Length(array('min' => 1)),
67+
)),
68+
'email' => new Assert\Email(),
69+
'simple' => new Assert\Length(array('min' => 102)),
70+
'gender' => new Assert\Choice(array(3, 4)),
71+
'file' => new Assert\File(),
72+
'password' => new Assert\Length(array('min' => 60)),
73+
));
74+
75+
$violations = $validator->validateValue($input, $constraint);
76+
5577
The ``validate()`` method returns a :class:`Symfony\\Component\\Validator\\ConstraintViolationList`
5678
object, which acts just like an array of errors. Each error in the collection
5779
is a :class:`Symfony\\Component\\Validator\\ConstraintViolation` object,

0 commit comments

Comments
 (0)