We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Validate a collection

Hi all, i am trying to find a good way to validate a collection of "documents" using Phalcon\Validation. For example, i could receive the next collection in a request:

"images": [
   {"external_reference": 88, "name": "some-image-001.jpg"},
   {"external_reference": 928, "name": "some-image-192.jpg"}
]

So, i need validate three stuff basically:

1) The image field is an array.

2) The image field size is greather than 0.

3) The image document must be have an external_reference and a name.

I thought write two custom validators:

<?php
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;

class DocumentCollection extends Validator implements ValidatorInterface {

    public function validate($validator, $attribute) {
        /* Validate is_array($attribute) and count($attribute) > 0 */
    }
}
<?php
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;

class ImageDocument extends Validator implements ValidatorInterface {

    public function validate($validator, $attribute) {
        /* Validate an image document && set filters */
    }
}

But, how i can set a relation between both validators ?

Any ideas ? Are there a better way ?

edited Sep '16

You can set 'relation' with DI. But, if that's JSON what you're getting in your app, perhaps you could validate it via JSON schema.