Laravel 5.2验证文件数组 [英] Laravel 5.2 Validate File Array

查看:81
本文介绍了Laravel 5.2验证文件数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三个字段的表单:titlebodyphoto[].我正在尝试对其进行验证,以便至少填写一项,但似乎无法正常工作.如果我上传文件,仍然会收到titlebody的错误.

I have a form with three fields: title, body and photo[]. I'm trying to validate it so that at least one item is filled in, but I can't seem to get it to work. If I upload a file I still receive an error for title and body.

public function rules()
{
    return [
        'title' => 'required_without_all:body,photo.*',
        'body' => 'required_without_all:title,photo.*',
        'photo.*' => 'required_without_all:title,body',
        'photo.*' => 'mimes:jpeg,gif,png',
    ];
}

更新:乔纳森(Jonathan)指出我的规则有误.我已经修复了它们,现在正在使用它.它仍然无法正常工作;当我尝试上传照片时,出现错误消息,要求其他字段.

Update: Jonathan pointed out that I had my rules wrong. I've fixed them and am now using this. It's still not working; when I try to upload a photo I get the error message that the other fields are required.

public function rules()
{
    return [
        'title' => 'required_without:body,photo.*',
        'body' => 'required_without:title,photo.*',
        'photo.*' => 'required_without:title,body|mimes:jpeg,gif,png',
    ];
}

推荐答案

如果要确保photo字段是数组,则需要'photo' => 'array',然后可以将'photo.*' => ''用于其他验证阵列的子级.

If you're looking to ensure the photo field is an array then you need 'photo' => 'array' and then you can use 'photo.*' => '' for the other validations of the array's children.

规则由竖线字符|分隔,因此,如果要在示例中将两者结合起来,则为'photo.*' => 'required_without_all:title,body|mimes:jpeg,gif,png',.我看不到您使用管道来分隔规则,所以我不确定您是否意识到这一点.

The rules are separated by a pipe character | so if you were going to combine the two in your example it would be 'photo.*' => 'required_without_all:title,body|mimes:jpeg,gif,png',. I don't see you using the pipe to separate rules so I can't be sure you are aware of it.

这可能是您一开始出错的地方(关联数组中的两个键相同),并且某种优先级会影响否定其中一个规则.

This may have been where you were going wrong in the first place (two keys in the associative array that are identical) and some kind of precedence taking affect negating one of the rules.

您可以尝试这样的操作(为了便于记录,我认为使用required_without_all是正确的选择,因为这规定了如果给定字段的 all 为缺少):

You could try something like this (for the record I think you were on the right track to begin with using required_without_all as this stipulates the need to be required if all of the given fields are missing):

public function rules()
{
    return [
        'title' => 'required_without_all:body,photo',
        'body' => 'required_without_all:title,photo',
        'photo' => 'array',
        'photo.*' => 'required_without_all:title,body|mimes:jpeg,gif,png',
    ];
}

参考

这篇关于Laravel 5.2验证文件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆