【问题标题】:Laravel: Sometimes rule not working on input type=fileLaravel:有时规则不适用于输入类型=文件
【发布时间】:2019-02-25 04:48:17
【问题描述】:

我正在创建一个 FormRequest,它根据其字段名称验证它是否包含图像。以下是我的规则:

public function rules(){
    return [
        'username'              => 'required|exists:users',
        'key'                   => 'required|exists:users,activation_key',
        'id'                    => 'sometimes|required|array|min:2',
        'id.*'                  => 'sometimes|required|file|mimes:jpeg,jpg,png|max:5000',
        'documents'             => 'sometimes|required|array|min:4',
        'documents.*'           => 'sometimes|required|file|mimes:jpeg,jpg,png,doc,pdf,docx,zip|max:5000',
        'g-recaptcha-response'  => 'required',
    ];
}

换句话说,上传文件的数组在设置时会被验证。我正在处理这个槽刀片。

我的请求通过Jquery.ajax() 完成,并使用new FormData($('selector')[0]) 获取字段值。我的 ajax 参数是正确的,所以这不重要。

问题是,在使用空白表单发出 HTTP 请求时,唯一正在验证的内容是 usernamekeyg-recaptcha-response

进一步调试表明,删除 sometimes 规则使其工作。但我只需要有条件地检查一个(例如/upload-id 将只显示id[] 字段,/upload-documents 将只显示document[] 字段)。

【问题讨论】:

  • 删除 sometimes|required 并仅使用 sometimes

标签: jquery ajax validation laravel-5 form-data


【解决方案1】:

原来问题是 laravel 在某种程度上忽略了空的 input[type=file] 数组并且没有将其添加到 Request 类的参数包中。我所做的解决方法是在数组项验证上使用required_if 规则,如下所示:

public function rules(){
    return [
        'username'              => 'required|exists:users',
        'key'                   => 'required|exists:users,activation_key',
        'account_type'          => ['required', Rule::in(['individual', 'business'])],
        'id'                    => 'nullable|array|min:2',
        'id.*'                  => 'required_if:account_type,individual|file|mimes:jpeg,jpg,png|max:5000',
        'documents'             => 'nullable|array|min:4',
        'documents.*'           => 'required_if:account_type,business|file|mimes:jpeg,jpg,png,doc,pdf,docx,zip|max:5000',
        'g-recaptcha-response'  => 'required'
    ];
}

在这里,我有一个决定因素,两者之间将被验证,所以如果 account_type = individal,它只会在 id 数组中更深地验证

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    相关资源
    最近更新 更多