0

I want to validate an array using validation group because of some conditions but validation group doesn't seem affect array?

$params = [
    'type' => 'a',
    'province' => 'b',
    'district' => 'c'
];

$constraints = new Collection([
    'type' => [new NotBlank()],

    'province' => [new NotBlank(['groups' => ['selection']])],
    'district' => [new NotBlank(['groups' => ['selection']])],

    'distance' => [new NotBlank(['groups' => ['location']])],
    'lat' => [new NotBlank(['groups' => ['location']])],
    'lon' => [new NotBlank(['groups' => ['location']])],
]);

$errors = $this->container->get('validator')->validate($params, $constraints, ['selection']);

Validation errors:

Array[distance]:
This field is missing. (code 1)
Array[lat]:
This field is missing. (code 1)
Array[lon]:
This field is missing. (code 1)

Thank for your help!

1 Answer 1

2

You need to use 'allowMissingFields' => true, like this :

$constraints = new Collection(
'allowMissingFields' => true,
'fields' => [
    'type' => [new NotBlank()],

    'province' => [new NotBlank(['groups' => ['selection']])],
    'district' => [new NotBlank(['groups' => ['selection']])],

    'distance' => [new NotBlank(['groups' => ['location']])],
    'lat' => [new NotBlank(['groups' => ['location']])],
    'lon' => [new NotBlank(['groups' => ['location']])],
]);

https://symfony.com/doc/2.7/reference/constraints/Collection.html

The CollectionValidator is checking if the field exists before the constraint NotBlank is validated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.