Laravel 5 FormRequest数组文件字段

时间:2015-04-24 09:22:04

标签: validation laravel-5

我们如何为表单数组字段设置自定义消息?让我通过向您展示我的一些代码来解释。

Form Field:
{!! Form::file('doc[]', array('multiple'=>true)) !!}

FormRequest:
public function validator($factory)
    {
        $v = $factory->make($this->all(), $this->rules());
        $v->each('doc', ['required','mimes:doc,docx,jpg,jpeg,png|max:2048']);
        return $v;
    }

默认显示:

  • doc.1必须是以下类型的文件:doc,docx,jpg,jpeg,png。
  • doc.2必须是以下类型的文件:doc,docx,jpg,jpeg,png。

但我想要节目

  • {filename}必须是以下类型的文件:doc,docx,jpg,jpeg,png。

3 个答案:

答案 0 :(得分:1)

我找到了为表单数组字段设置自定义消息的方法。

public function validator($factory)
    {
        $messages = [
            'doc.0.required' => "You must provide at least one document.",
        ];

        if(Request::hasFile('doc')) {
            $docs = Request::file('doc');
            foreach ($docs as $key => $val) {
                $messages['doc.' . $key . '.mimes'] = 'The document ' . $val->getClientOriginalName() . ' must be a file of type: :values.';
                $messages['doc.' . $key . '.max'] = 'The document ' . $val->getClientOriginalName() . ' may not be greater than :max kilobytes.';
            }
        }

        $v = $factory->make($this->all(), $this->rules(),$messages);
        $v->each('doc', ['required','mimes:pdf,doc,docx,jpg,jpeg,png|max:2048']);
        return $v;
    }

答案 1 :(得分:0)

绝对有可能。一种方法是覆盖validation.php中的语言文件,或者遵循http://laravel.com/docs/5.0/validation#custom-error-messages中定义的任何其他方法

在validation.php中你会找到

"mimes"                => "The :attribute must be a file of type: :values.",

将其更改为

"mimes"                => "The documents must be a file of type: :values.",

如果您想在邮件中包含文件名,请执行以下操作

$messages = [
  'mimes' => "The $fileName must be a file of type: :values.",
];    
$v = $factory->make($input, $rules, $messages);

答案 2 :(得分:0)

 $file = $request->file('user_detail');
    $credentials =[
        'file'      => $file,
        'extension' => strtolower($file->getClientOriginalExtension()),
    ];

    $rules = [
        'file'          => 'required',
        'extension'      => 'required|in:xlsx',
    ];
    $msg = [
        'file.required' => "file is required.",
        'extension.in' => "only accept .xlsx file.",

    ];

    $validator = Validator::make($credentials,$rules,$msg);
    if($validator->fails())
    {
        return $validator->messages()->all();
    }