Laravel``有时''验证器因嵌套数组而失败

编程入门 行业动态 更新时间:2024-10-20 03:20:48
本文介绍了Laravel``有时''验证器因嵌套数组而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Laravel Validator类对数组进行一些基本验证.

Am using the Laravel Validator class to do some basic validation on an array.

我的数组:

$employee['name']='name'; $employee['address']='address'; $employee['department']['department_name']='deptname'; $employee['department']['department_address']='deptaddress';

我的验证规则如下:

$rules = array( 'name'=> 'required', 'address' => 'required', 'department.department_name' => 'sometimes|required' )

以及以下自定义消息:

$messages = array( 'name.required' => 'Employee Name is required', 'address.required' => 'Address is required' 'department.department_name.required' => 'Department name is required' )

我将使用Validator::make($employee, $rules, $messages);

根据我的规则,只有在数组中存在department_name时,才应验证department_name.但是,当前Validator存在且为空时,尚未验证department_name.有什么想法我可能做错了吗?

As per my rules, department_name should be validated if and only if it is present in the array. But currently the Validator is not validating department_name when its present and blank. Any ideas what I might be doing wrong?

推荐答案

您在这里出错了,请参见文档此处

You are going a bit wrong here see the docs here

在那里提到如果我有$photos['profile'],那么我的验证将像这样

it is mentioned there If I have $photos['profile'] then my validation will go like this

$validator = Validator::make($request->all(), [ 'photos.profile' => 'required|image', ]);

在上面的示例中,您的情况应该是这样

From the above example, In your case it should be like this

$rules = array( 'name'=> 'required', 'address' => 'required', 'employee.department.department_name' => 'sometimes|required' )

因为您有这样的数组$employee['department']['department_name']

$message也会这样

$messages = array( 'name.required' => 'Employee Name is required', 'address.required' => 'Address is required' 'employee.department.department_name.required' => 'Department name is required' )

更多推荐

Laravel``有时''验证器因嵌套数组而失败

本文发布于:2023-11-12 12:17:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   数组   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!