Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate max number of multiple files that can be attached in Laravel Validation

I have a form that allows multiple files to be attached.

I am validating the form for attachment field as:

$this->validate($request, [

            'attachments.*' => 'mimes:jpg,jpeg,bmp,png|max:5000',
        ]);

It works properly but I also want to only allow maximum of 3 files to be uploaded at a time.

How do I achieve this ?

like image 761
Raj Avatar asked Jun 26 '18 07:06

Raj


2 Answers

As attachments is an array, you can use max rule to validate it max elements as 3

 $messages = [
    "attachments.max" => "file can't be more than 3."
 ];

 $this->validate($request, [

        'attachments.*' => 'mimes:jpg,jpeg,bmp,png|max:5000',
        'attachments' => 'max:3',
    ],$messages);
like image 52
freelancer Avatar answered Nov 03 '22 11:11

freelancer


There is option to add Custom Validation Rules in laravel.

Also you can try something like this:

$this->validate($request, [
    'attachments.*' => [
        'mimes:jpg,jpeg,bmp,png',
        function($attribute, $value, $fail) {
            if (count($value) > 3) {
                return $fail($attribute . ' should be less than or equal to 3.');
            }
        },
    ]
]);

There is another solution posted here: How to validation number of files

like image 3
Lovepreet Singh Avatar answered Nov 03 '22 12:11

Lovepreet Singh