简体   繁体   English

如何验证Laravel中的数组输入?

[英]How can I validate array inputs in Laravel?

This is my code: 这是我的代码:

public function store(Request $request)
{
    try {
        $this->validate($request, [
            'activity_licenses' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:6144',
        ]);
    } catch (\ValidationException $e) {
        return [false, $e->getMessage()];
    }
    .
    .
    .

Actually activity_licenses is an array. 实际上activity_licenses是一个数组。 This is the HTML: 这是HTML:

<input type="file" name="activity_licenses[] />
<input type="file" name="activity_licenses[] />

How can I validate that? 我该如何验证? And more important that, how can I catch the reason of failure (error message) ? 更为重要的是,我该如何捕捉失败原因(错误消息) Currently $e->getMessage() is empty on failure. 当前$e->getMessage()在失败时为空。

Try: 尝试:

$input_data = $request->all();

$validator = Validator::make(
    $input_data, [
    'image_file.*' => 'required|mimes:jpg,jpeg,png,bmp|max:20000'
    ],[
        'image_file.*.required' => 'Please upload an image',
        'image_file.*.mimes' => 'Only jpeg,png and bmp images are allowed',
        'image_file.*.max' => 'Sorry! Maximum allowed size for an image is 20MB',
    ]
);

if ($validator->fails()) {
    // Validation error.. 
}

https://stackoverflow.com/a/38327539/3475207 https://stackoverflow.com/a/38327539/3475207

Array validation is describe in Laravel doc and using your case, it should be: Laravel文档中描述了数组验证,并根据您的情况进行说明:

$this->validate($request, [
        'activity_licenses.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:6144',
    ])

Using the $this->validate() in the controller, the error messages are automatically passed to your views, and the variable $errors holds it. 使用控制器中的$this->validate() ,错误消息将自动传递到您的视图,变量$errors保留它。 You should check: Working with Error messages in the Laravel doc 您应该检查:在Laravel文档中使用错误消息

An example is (taken from the doc): 一个例子是(摘自文档):

@if ($errors->any())
<div class="alert alert-danger">
    <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>

@endif @万一

You may want to validate by calling the validator manually this way: 您可能希望通过以下方式手动调用验证器进行验证:

$validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

My advice is that you should read the documentation. 我的建议是您应该阅读文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM