php - 为什么 Laravel 5.6 中的自定义验证不起作用?
问题描述
我使用 php artisan make:rule 创建了一个自定义规则,将其设置在控制器中,但它不起作用。可能是什么问题?
class CheckDeliveryDate implements Rule
{
public $client_id;
private $is_after_midday;
private $error_messge;
public function __construct(int $client_id)
{
$this->client_id = $client_id;
$this->is_after_midday = Carbon::now()->greaterThan(Carbon::now()->midDay());
$this->error_messge = 'Error';
}
public function passes($attribute, $value)
{
$delivery_date = Carbon::parse($value);
if ($delivery_date->isToday()) {
$this->error_messge = 'Error';
return false;
}
if ($delivery_date->endOfDay()->isPast()) {
$this->error_messge = 'Error';
return false;
}
return true;
}
public function message()
{
return $this->error_messge;
}
}
在控制器中我设置方法规则:
public function rules($client_id)
{
return [
'orders.*.positions.*.delivery_time' => [
'required',
'date',
new CheckDeliveryDate($client_id)
],
];
}
当我存储订单时,validator->fails() 返回“false”。
$validator = Validator::make(
$request->all(),
$this->rules($client_id)
);
我尝试在规则中设置 dd 或转储,但不起作用。我的错误在哪里?
解决方案
如 laravel 文档(https://laravel.com/docs/5.8/validation#custom-validation-rules)所述,您不应该将参数传递给您的自定义规则实例。Laravel 为你做到了。
因此:
new CheckDeliveryDate($client_id)
变成:
new CheckDeliveryDate
祝你今天过得愉快 !
推荐阅读
- tfs - 如何在 azure devops 服务中设置并发构建 - tfs
- java - Jenkins 使用 Maven 依赖项构建失败
- python - Sending long messages on CAN FD using python-can library on vector hardware
- typescript - 使用 VSCode API 获取活动格式化程序列表
- wordpress - Wordpress post__not_in 不能在 WP_Query 循环中工作
- json - Deserialize JSON object which has property name as number into a object in VB.NET
- phalcon - Phalcon PHP 3.4 文档和教程是否有 github repo 版本、分支或标签?
- jquery - 如何完成一次向一个项目添加类(WayPoints)
- javascript - 如何修复 undefined is not an object on setState in react native
- python - 对存储元组列表的字典中的值求和