Home > Enterprise >  Laravel file type validation for unrecognised file types
Laravel file type validation for unrecognised file types

Time:12-03

I'm trying to validate file types in Laravel like this:

'rules' => ['mimes:pdf,bdoc,asice,png,jpg']

Validation works correctly for pdf, png and jpg but does not work for bdoc or asice files (files with those extensions do not pass validation).

My guess is that it probably does not work for those file types because they are not included in the MIME types shown here: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

Am I correct in that assumption? If so, how can I validate these file types?

CodePudding user response:

You need to create a custom validation rules for that specific file types.

Check the documentations on creating a custom validation here. https://laravel.com/docs/8.x/validation#custom-validation-rules

Update: Added some sample codes.

Validation Rule

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class AcceptableFileTypesRule implements Rule
{
    protected array $acceptableTypes = [];

    public function __construct(array $acceptableTypes = [])
    {
        $this->acceptableTypes = $acceptableTypes;
    }

    /**
     * @param string $attribute
     * @param \Illuminate\Http\UploadedFile $value
     *
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        return in_array($value->getClientOriginalExtension(), $this->acceptableTypes);
    }

    public function message(): string
    {
        // Change the validation error message here
        return 'The validation error message.';
    }
}

You can use it like this

[
   'rules' => ['required', new App\Rules\AcceptableFileTypesRule(['pdf,bdoc,asice,png,jpg'])]
]
  • Related