laravel验证条件图像场

时间:2019-01-13 10:40:32

标签: laravel validation

我有一个必填字段,可以是2个值类型:字符串(路径)和图像文件

如何为此编写验证规则?

如果值是字符串,则检查file_exist,如果文件是图像,则为

谢谢

2 个答案:

答案 0 :(得分:1)

也许有更简单的方法可以做到这一点。但是,我认为这样的自定义规则应该有效。

$validator = Validator::make($request->all(), [
    'image' => [
        'required',
        function ($attribute, $value, $fail) {
            if(is_file($value)) {
                if (true !== mb_strpos($value->getMimeType(), "image")) {
                    return $fail($attribute.' is invalid.'); 
                }
            }
            if (is_string($value)) {
                if(! file_exists($value)) {
                    return $fail($attribute.' is invalid.'); 
                }
            }
        },
    ],
]);

答案 1 :(得分:1)

我找到了FormRequest的答案

MyTestFormRequest

<?php
use Illuminate\Foundation\Http\FormRequest;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class MyTestFormRequest extends FormRequest
{
    public function rules()
    {
        $rules = [
            "image" => ['required']
        ];
        if(is_string($this->image)) {
            $rules['image'][] = new FileExistsRule;
        } else if($this->image instanceof UploadedFile) {
            $rules['image'][] = 'image';
            $rules['image'][] = 'dimensions:ratio=1/1';
        }

        return $rules;
    }
}

FileExistsRule

<?php

use Illuminate\Contracts\Validation\Rule;

class FileExistsRule implements Rule
{
    public function passes($attribute, $value)
    {
        return file_exists(public_path($value));
    }

    public function message()
    {
        return 'The file not exists';
    }
}