Limit number of files that can be uploaded

前端 未结 2 1343
礼貌的吻别
礼貌的吻别 2021-01-15 18:31

How can I limit the number of files that can be uploaded?

The max validation seems to apply to the size of the image (in kilobytes). How can I make a va

2条回答
  •  终归单人心
    2021-01-15 19:06

    In laravel, there is no built-in validation rule for that. But you can create custom-validation rule to handle this.

    Here is a simple custom-validation rule for it.

    Create customValidator.php in app/ directory.

    Validator::extend('upload_count', function($attribute, $value, $parameters)
    {   
        $files = Input::file($parameters[0]);
    
        return (count($files) <= $parameters[1]) ? true : false;
    });
    

    Don't forget to add it to app/start/global.php

    require app_path().'/customValidator.php';
    

    In your validation setting,

    $messages = array(
        'upload_count' => 'The :attribute field cannot be more than 3.',
    );
    
    $validator = Validator::make(
        Input::all(),
        array('file' => array('upload_count:file,3')), // first param is field name and second is max count
        $messages
    );
    
    if ($validator->fails()) {
         // show validation error
    }
    

    Hope it will be useful for you.

提交回复
热议问题