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!
My Answer:
You can achieve this by using the All constraint inside the 'pictureUrls' field definition. The All constraint allows you to apply constraints to each element of an array. Here's how you can modify your code:
php
$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 All([
new Url(),
]),
],
],
]);
By adding the All constraint with the Url constraint inside the 'pictureUrls' field definition, you are telling Symfony to apply the Url constraint to each element of the 'pictureUrls' array. This way, each element in the 'pictureUrls' array will be validated as a URL.
Rate this post
4 of 5 based on 1760 votesComments