Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel file type validation for unrecognised file types

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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'])]
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading