仅当值不为空时,Laravel 才请求验证规则?
Posted
技术标签:
【中文标题】仅当值不为空时,Laravel 才请求验证规则?【英文标题】:Laravel Requests Validation rules only if value is not null? 【发布时间】: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
规则?
【参考方案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'],
];
【讨论】:
以上是关于仅当值不为空时,Laravel 才请求验证规则?的主要内容,如果未能解决你的问题,请参考以下文章