Ive tried creating my validator but it does not work. Documentation does not help because it only cares for object validation and has one example for array validation.
Im trying to validate my data based on fields sent with the data.
So im having a field type
in the request which is either credentials
, google
or facebook
and depending on this fields value the other fields should be validated.
Of course the type
has to be validated first.
What I tried was following the documentation for collections but I only get unexpected Exceptions and results. Sometimes errors, sometimes dont, the thing just does not work as expected.
Given the following example:
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
require_once(__DIR__ . "/../vendor/autoload.php");
$validator = Validation::createValidator();
$constraints = new Assert\Collection([
"type" => [
new Assert\Required([
"groups" => ["type"],
"constraints" => new Assert\Choice([
"choices" => ["credentials", "facebook", "google"],
])
]),
],
"username" => [
new Assert\NotBlank([
"groups" => ["credentials", "facebook", "google"]
])
],
"password" => [
new Assert\NotBlank([
"groups" => ["credentials"]
]),
new Assert\Length([
"min" => 6,
"groups" => ["credentials"]
]),
],
"passwordConfirm" => [
new Assert\NotBlank([
"groups" => ["credentials"],
]),
new Assert\IdenticalTo([
"groups" => ["credentials"],
"propertyPath" => "password"
])
]
]);
$data = [];
$errors = $validator->validate($data, $constraints, "credentials");
foreach ($errors as $error) {
echo $error->getPropertyPath() . ": " . $error->getMessage() . "<br />";
}
Will output:
[type]: This field is missing.
[username]: This field is missing.
[password]: This field is missing.
[passwordConfirm]: This field is missing.
Even though I have explicitly passed "credentials"
to groups.
Ive also tried using the fields
option but it introducec more problems.
Does anyone know how to use the validator properly and use groups to actually only validate subsets of data.