5

I am trying to validate an uploaded csv file with

$validator = Validator::make(
        [
            'file'      => $file,
            'extension' => strtolower($file->getMimeType()),
        ],
        [
            'file'      => 'required|in:csv',
        ]
    );

The validator fails on giving a valid csv file with message The file must be a file of type: csv.

The validator passes if i remove in:csv.

Am i doing something wrong?

PS - $file is available and of standard upload file type object(Symfony\Component\HttpFoundation\File\UploadedFile)

3 Answers 3

12

Try changing

$validator = Validator::make(
    [
        'file'      => $file,
        'extension' => strtolower($file->getMimeType()),
    ],
    [
        'file'      => 'required|in:csv',
    ]
);

To

$validator = Validator::make(
    [
        'file'      => $file,
        'extension' => strtolower($file->getClientOriginalExtension()),
    ],
    [
        'file'          => 'required',
        'extension'      => 'required|in:csv',
    ]
);
5
  • Tried that. Gives the same error. PS - I am using Laravel 5 Mar 20, 2015 at 11:21
  • Okay what is the error when using mimes? Also why are you not using a request for your validation, if using Laravel 5 Mar 20, 2015 at 11:49
  • Okay I see what you are doing now, Mar 20, 2015 at 11:53
  • how to get this in Request object? Apr 15, 2016 at 19:06
  • what is $file ?? what you storing in $file ?
    – Aamir
    Jul 15, 2016 at 5:43
4

If you're uploading a CSV file, you should allow the following mime types:

'application/vnd.ms-excel','text/plain','text/csv','text/tsv'

Also in Laravel 5:

$rules =  [
    'file'          => 'required',
    'extension'      => 'required|mimes:csv'
];

From the docs: (http://laravel.com/docs/5.0/validation)

The Validator class provides several rules for validating files, such as size, mimes, and others. When validating files, you may simply pass them into the validator with your other data.

1
  • This is the best answer
    – Adam Pery
    Jun 5, 2020 at 10:18
1
//custom vaildation for csv file
$this->validate(request(), [
    'file' => ['required',function ($attribute, $value, $fail) {
        if (!in_array($value->getClientOriginalExtension(), ['csv','xsl','xsls'])) {
            $fail('Incorrect :attribute type choose.');
        }
    }]
]);
1
  • No need to do any extra thing, you just copy above code & use. its work for any type of mimes validation. Nov 22, 2020 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.