ahmeda's avatar

mimes:ttf does not working in validation

I have a file with TTF extension I need to validate

 $request->validate([
       'font' => 'required|file|mimes:ttf',
  ]);

When I upload the ttf file the validation says The font must be a file of type ttf,.

I already put enctype="multipart/form-data" in form!

0 likes
1 reply
rodrigo.pedra's avatar
Level 56

As said in the docs:

Even though you only need to specify the extensions, this rule actually validates the MIME type of the file by reading the file's contents and guessing its MIME type.

reference: https://laravel.com/docs/9.x/validation#basic-usage-of-mime-rule

What it means is that it checks on the content of the files to determine its mime type, the extension actually does not matter.

I had some difficulties with this in other projects, not with ttf specifically, as the file linux utility, which is used by the Symfony component powering this validation sometimes return a different mimetype than we usually expect.

For example, I took a local ttf file to check its mimetype:

$ file -i InputSerif_Italic.ttf
InputSerif_Italic.ttf: font/sfnt; charset=binary

As you can see the mime type returned is font/sfnt , which, from the reference Laravel docs provide on the link above, does not map to any extension at all. The expected mimetype for a ttf would be font/ttf

What you could do is specify multiple mimetypes that you can accept, using the mimetypes validation rule instead:

$request->validate([
    'font' => ['required', 'file', 'mimetypes:font/ttf,font/sfnt'],
]);

reference: https://laravel.com/docs/9.x/validation#rule-mimetypes

Hope this helps.

3 likes

Please or to participate in this conversation.