I'm trying to use Symfony Validator on a file upload form (form extension's validation) and I'm getting this error message:
messageTemplate: "This value should be of type string." from Symfony\Component\Validator\ConstraintViolation
Upload works well without the validator, and I cant figure out where this message is coming from.
Here's my FormType, with a basic validation as doc's exemple:
{
$builder
->add('file', FileType::class, [
'label' => 'Choisir un fichier',
'mapped' => false,
'multiple' => true,
'constraints' => [
new File([
'maxSize' => '1024k',
'mimeTypes' => [
'application/pdf',
'application/x-pdf',
],
'mimeTypesMessage' => 'Please upload a valid PDF document',
])
],
])
;
}
If I remove maxSize
, mimeTypes
and/or mimeTypesMessage
arguments, I still have the same problem.
I can't use annotations on entity (mapped option is set to false
).
Using Javascript, we could easily validate the file type by extracting the file extension with the allowed file types. Below is the sample example for the file type validation. In this example, we upload files having extensions .jpeg/.jpg/.png/.gif only.
If the value is mandatory, a common solution is to combine this constraint with NotNull. It defines the validation group or groups of this constraint. Read more about validation groups. type: string default: This value should be of type { { type }}. The message if the underlying data is not of the given type.
Use the following steps to upload multiple file with validation in laravel 8 applications: First of all, download or install laravel 8 new setup. So, open terminal and type the following command to install new laravel 8 app into your machine: In this step, setup database with your downloded/installed laravel 8 app.
Read more about validation groups. type: string default: This value should be of type { { type }}. The message if the underlying data is not of the given type. You can use the following parameters in this message:
The error is due to the File
constraint expecting a filename, but since the field has the option multiple
is actually receiving an array. To solve it, you have to wrap the constraint in another All
constraint, that will apply the inner constraint (File
in this case) to each element of the array.
Your code should look like this:
->add('file', FileType::class, [
'label' => 'Choisir un fichier',
'mapped' => false,
'multiple' => true,
'constraints' => [
new All([
'constraints' => [
new File([
'maxSize' => '1024k',
'mimeTypesMessage' => 'Please upload a valid PDF document',
'mimeTypes' => [
'application/pdf',
'application/x-pdf'
]
]),
],
]),
]
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With