php - Laravel 5.2 验证规则顺序
问题描述
我做了一个自定义验证规则,它遍历包含一个键的对象数组,dates
并检查这些日期是否是连续的(日期之间的差异仅为 1 天)。为此,我需要填写“日”键并具有正确的日期格式。我将date_format
验证器规则放在day
键中,但由于我的自定义规则在数组字段中,当我没有给他正确的 date_format(例如随机字符串)时它会崩溃。也许您对代码的理解更好。
自定义验证器规则
Validator::extend('consecutive_dates', function($attribute, $value, $parameters, $validator) {
// Order the in the array with the 'day' value
usort($value, array($this, 'compare_dates'));
$previous_date = null;
foreach ($value as $date) {
// Check if dates are consecutives
$current_date = new DateTime($date['day']);
if ($previous_date !== null) {
$interval = $current_date->diff($previous_date);
if ($interval->days !== 1) {
// If not, fails
return false;
}
}
$previous_date = $current_date;
}
return true;
);
规则定义
'dates.*.day' => 'required_with:dates|date_format:Y-m-d',
'dates' => 'bail|array|filled|consecutive_dates',
现在,如果我尝试验证这样的事情:
"dates": [{
"day": "fdsa",
}]
它会崩溃并说
DateTime::__construct(): Failed to parse time string (fdsa) at position 0 (f): The timezone could not be found in the database
问题是:有没有办法告诉 Laravel 首先 Validate that 'dates.*.day'
must havedate_format: Y-m-d
这样它就不会在自定义验证中失败?
解决方案
您应该首先检查给定值是否有效日期,像这样
if (Carbon::createFromFormat('date format', $date['day']) !== false) {
// valid date
}
我希望这将有所帮助。
推荐阅读
- azure-ad-b2c - 从 AD B2C 自定义策略中的 url 收集 id_token_hint 的值
- javascript - Sequelize Reuse Query 在另一个查询中
- sql - 具有多行的 Id 的 SQL Case When 语句
- c++ - C++ 20 概念:要求运算符重载
- python - 从 Flask 下载数据帧为 csv
- c++ - 如何在 GTK 程序运行时禁用屏幕保护程序/电源管理/屏幕黑屏?
- azure-artifacts - 上游通用包神器提要
- sql-server - 基于来自另一个查询的列表的 SQL 查询
- c++ - 对象销毁会使指针无效吗?
- python - 使用 anaconda 在虚拟环境中为不同的项目安装包