我需要扩展laravel验证器来创建一个新的验证器,但问题是我需要传递2个参数,一个用于days
,一个用于slots
。怎么解决这个问题?
示例dd($request->all)
转储:
array:2 [
"days" => array:2 [
0 => "1" // Mon
1 => "2" // Tue
]
"slots" => array:2 [
1 => array:2 [
"open" => "09:00"
"close" => "11:30"
]
2 => array:2 [
"open" => "16:00"
"close" => "21:00"
]
]
]
需要循环浏览days
并查看slots
。
伪代码,例如:
foreach($days as $day) {
foreach($slots as $slot)
{
// Validation Logic for $day and $slot (open and close)
}
}
答案 0 :(得分:2)
这是制作自定义Laravel验证的正确方法
使用
创建您自己的验证服务提供商php artisan make:provider ValidationServiceProvider
然后转到config\app.php
并将其添加到providers
App\Providers\ValidationServiceProvider::class
现在转到ValidationServiceProvider.php
并添加
use Validator;
到顶部......
,这在boot()
函数
Validator::extend('days_with_slots', function($attribute, $value, $parameters, $validator) {
$slots = request()->get('slots');
if(!is_array($slots)) return false;
foreach($days as $day) {
foreach($slots as $slot) {
if(empty($slot[$day]) || empty($slot[$day]['open'] || empty($slot[$day]['close']))) {
return false;
}
}
}
});
最后,在你的规则中使用它
$rules['slots'] = 'days_with_slots'
您还可以为其添加自定义消息,例如
$message['days_with_slots'] = 'Open and Close Timings are required for the days selected'
希望这会有所帮助:)
答案 1 :(得分:1)
嗯,这是另一种方法。
在AppServiceProvider中,使用boot()
方法添加自定义处理程序:
\Validator::resolver(function($translator, $data, $rules, $messages) {
return new MyCustomValidator($translator, $data, $rules, $messages);
});
创建解析程序类:
class MyCustomValidator extends Illuminate\Validation\Validator;
{
public function validateSlotsInDays($attribute, $value, $parameters){
$valid = false;
$days = \Request::input($parametros[0]);
$slots = $value;
foreach($days as $day) {
foreach($slots as $slot) {
// Validation Logic for $day and $slot (open and close)
}
}
return $valid;
}
public function validateSlot($attribute, $value, $parameters){
$valid = false;
$days = \Request::input($parametros[0]);
$slot = $value;
foreach($days as $day) {
// do whatever here
}
return $valid;
}
}
最后,应用规则。如果您需要在至少一个插槽关闭时显示错误,则可以使用此规则:
$rules = [
'slots' => ['slots_in_days:days'],
];
了解我如何将days
作为参数传递。此外,如果您需要单独验证每个插槽并为每个插槽显示一条消息,请应用以下规则:
$rules = [
'slots.*' => ['slot:days'],
];
附加文档: