【问题标题】:Laravel Requests Validation rules only if value is not null?仅当值不为空时,Laravel 才请求验证规则?
【发布时间】:2021-04-18 01:17:07
【问题描述】:

我已为名为 CandidateProfileUpdateRequest.php 的更新方法创建了一个请求:

public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'photo' => ['mimes:jpeg,png,jpg,gif,bmp', 'max:4096'],
        'video_one' => ['mimes:mp4,mov,ogg,qt', 'max:30720'],
        'video_two' => ['mimes:mp4,mov,ogg,qt', 'max:30720'],
        'video_three' => ['mimes:mp4,mov,ogg,qt', 'max:30720'],
        'resume' => ['mimes:doc,docx,pdf', 'max:4096'],
        'job_title' => ['required'],
    ];
}

public function messages()
{
    return [
        'photo.max' => 'The photo may not be greater than 4MB.',
        'video_one.max' => 'The video may not be greater than 30MB.',
        'video_two.max' => 'The video may not be greater than 30MB.',
        'video_three.max' => 'The video may not be greater than 30MB.',
        'resume.max' => 'The resume may not be greater than 4MB.',
    ];
}

对于这 4 个不需要的字段 photo, video_one, video_two, video_three, 我只想应用这些规则,如果在这些表单字段中的任何一个中上传文件。

因此,例如,如果 video_two 为空,即用户未在此处上传任何内容,然后单击更新,则它不应返回 video_two 的任何规则。这可能吗?

【问题讨论】:

  • 您是否尝试过使用nullable 规则?

标签: laravel validation


【解决方案1】:

sometimes 规则不起作用。感谢 lagbox,nullable 规则奏效了!

【讨论】:

    【解决方案2】:

    查看sometimes 规则。

    在某些情况下,您可能希望仅当正在验证的数据中存在该字段时才对该字段运行验证检查。要快速完成此操作,请将有时规则添加到您的规则列表中:

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'photo' => ['mimes:jpeg,png,jpg,gif,bmp', 'max:4096'],
            'video_one' => ['mimes:mp4,mov,ogg,qt', 'max:30720'],
            'video_two' => ['sometimes', 'mimes:mp4,mov,ogg,qt', 'max:30720'],
    //                      ^^^^^^^^^^^
            'video_three' => ['mimes:mp4,mov,ogg,qt', 'max:30720'],
            'resume' => ['mimes:doc,docx,pdf', 'max:4096'],
            'job_title' => ['required'],
        ];
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-21
      • 2021-07-20
      • 2017-08-12
      • 2020-07-17
      • 2019-10-09
      • 2018-10-06
      • 2017-11-19
      • 1970-01-01
      • 2018-07-18
      相关资源
      最近更新 更多