laravel - 在 Laravel 中添加自定义验证时,类 Closure 的对象无法转换为字符串
问题描述
我正在研究 Laravel 中的一些自定义验证规则,其中添加了一些自定义验证 2 个日期,其中返回日期必须在出发日期后 6 天,当我添加自定义验证时,我不断收到以下错误:
(1/1) 在 ValidationRuleParser.php 第 107 行中,Closure 类的 ErrorException 对象无法转换为字符串
请协助
控制器
public function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'departure_date' => 'required|date|after:now',
//Must be 6 days after departure date
'return_date' => ['required', 'date', function ($attribute, $value, $fail) {
if (strtotime($value) < strtotime(request('departure_date')) + 518400) {
$fail('Departure date invalid');
}
}],
]);
}
解决方案
正如您在评论中提到的,您使用的 Laravel 版本不支持回调验证规则,不幸的是,您可以做到这一点的唯一方法是使用新规则扩展验证器。
将此添加到您的服务提供商之一(例如AppServiceProvider
)
public function boot() {
//Other boot things
$validator = app()->make(\Illuminate\Validation\Factory::class);
$validator->extend('return_date_after', function ($attribute, $value, $parameters, $validator) {
$otherAttribute = array_get($parameters, 0);
$days = array_get($parameters, 1, 6); //default 6 days
$otherValue = array_get($validator->getData(), $otherAttribute);
if (strtotime($value) < strtotime($otherValue) + $days*24*60*60) {
return false;
}
return true;
});
$validator->replacer('return_date_after', function ($message, $attribute, $rule, $parameters) {
return 'Your return date must be '.array_get($parameters,1,6).' days after your '.array_get($parameters, 0);
});
}
然后您可以将此自定义规则用作:
$validation = $this->validate($request, [
'departure_date' => 'required|date|after:now',
//Must be 6 days after departure date
'return_date' => ['required', 'date', 'return_date_after:departure_date,6' ]
]);
请注意,替换器$message
中的 来自 ,resources/lang/<locale>/validation.php
因此您可以在其中添加一个条目,例如“return_date_after”并在替换器中对其进行操作,而不是返回静态文本。例如:
"return_date_after" => "Your :attribute must be :days days after your :other_attribute"
然后你的替代者可以是:
$validator->replacer('return_date_after', function ($message, $attribute, $rule, $parameters) {
return str_replace([ ":days", ":other_attribute" ],
[ array_get($parameters, 1, 6), array_get($parameters,0) ],
$message);
});
推荐阅读
- python-3.x - 将 pyttsx3 与 tkinter 一起使用会导致程序停止并关闭,有什么想法吗?
- javascript - jQuery顺序函数在每个循环中一个接一个
- windows - 解析 Netsh 输出
- ruby-on-rails - Ruby on Rails 通过多个连接表访问数据
- python - 如何在matplotlib中绘制多条线,每条线的值数量不同
- pandas - 如何根据其他列的匹配索引将列表返回到数据框中
- r - R Markdown,在不同的div标签中创建for循环图
- html - 如何在 html 模板中显示 nut、date 字段?如何访问 html 模板中的外键字段?
- c++ - 在 Mac 上使用 CMake 的 GLFW
- react-native - 当在 Native-base Tabs 中调用 onChnageTab 函数时,如何将我的动态 id 传递给选项卡