如果字段是输入类型文件,则laravel中的required_if验证不会给出错误

时间:2018-09-14 05:48:06

标签: php laravel validation laravel-5.6

我有一种形式,其中有5个文本字段和2个输入类型文件字段。 对于所有7个字段,我都在laravel中编写了自定义验证规则,并且如果类型是业务,我希望所有字段都是必需的,所以我在所有字段中都使用了required_if,对于文本字段来说它是有效的,但是对于图像(输入类型文件)它就不起作用它始终认为是请求中存在的文件,如果在我将其更改为要求时未上传文件,则不会给出任何错误,因为它只会给我输入类型文件的错误。

public function rules()
{
    return [
        'country'       => 'required_if:type,business',
        'country2'      => 'required_if:type,business',
        'company'       => 'required_if:type,business',
        'number' => 'required_if:type,business',
        'expiry' => 'required_if:type,business',
        'profile_pic'       => 'required_if:type,business  |  mimes:jpeg,jpg,png,pdf',
        'document_pic'      => 'required_if:type,business  |  mimes:jpeg,jpg,png,pdf',
    ];
}

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

public function rules()
{
    return [
        'country'       => 'required_if:type,business',
        'country2'      => 'required_if:type,business',
        'company'       => 'required_if:type,business',
        'number'        => 'required_if:type,business',
        'expiry'        => 'required_if:type,business',
        'profile_pic'   => 'required_if:type,business|image',
        'document_pic'  => 'required_if:type,business|image',
    ];
}

还可以编辑我的:https://laravel.com/docs/5.3/validation#rule-mimes

答案 1 :(得分:0)

该问题是由于多余的空间无效规则而引起的。 删除了if和mime类型所需的空格及其正常工作。

public function rules()
{
    return [
        'country'       => 'required_if:type,business',
        'country2'      => 'required_if:type,business',
        'company'       => 'required_if:type,business',
        'number' => 'required_if:type,business',
        'expiry' => 'required_if:type,business',
        'profile_pic'       => 'required_if:type,business|mimes:jpeg,jpg,png,pdf',
        'document_pic'      => 'required_if:type,business|mimes:jpeg,jpg,png,pdf',
    ];
}