Home > Blockchain >  Symfony Collection Validation
Symfony Collection Validation

Time:07-28

I've building a quick API with Symfony 6.1 and custom validators to validate my inputs, and I'm struggling with the syntax.

I made this:

$constraint = new Collection([
            'fields' => [
                'discordId' => [
                    new Type(['type' => 'numeric']),
                    new NotBlank(),
                ],
                'discordHandle' => [
                    new Type(['type' => 'string']),
                    new NotBlank(),
                    new Regex([
                        'pattern' => '/^((.{2,32})#\d{4})/',
                        'message' => 'Please provide a valid Discord handle (eg. USERNAME#1234).',
                    ]),
                ],
                'pictureUrls' => [
                    new Type(['type' => 'array']),
                    new NotBlank(),
                    new Count(['min' => 1, 'max' => 5]),
                    //new Url(),
                ],
            ],
        ]);

It works fine until I re-enable the Url() constraint, then it expects the "pictureUrls" fields to be a string and not an array anymore.

My syntax must be wrong but I don't understand how I can make it to expect "pictureUrls" to be an array containing Urls.

Can anyone help, please?

Thanks!

CodePudding user response:

If I'm reading the docs right, I'm pretty sure you wan to do:

            'pictureUrls' => [
                new Type(['type' => 'array']),
                new NotBlank(),
                new Count(['min' => 1, 'max' => 5]),
                new All([
                    new Url(),
                ])
            ],
  • Related