【发布时间】:2018-11-25 01:15:43
【问题描述】:
我做了一个自定义验证规则,它遍历包含键 dates 的对象数组,并检查这些日期是否是连续的(日期之间的差异仅为 1 天)。为此,我需要填写“日”键并具有正确的日期格式。我将date_format 验证器规则放在day 键中,但由于我的自定义规则在数组字段中,当我没有给他正确的日期格式(例如随机字符串)时它会崩溃。也许你对代码的理解更好。
自定义验证器规则
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 首先验证 'dates.*.day' 必须有 date_format: Y-m-d 这样自定义验证不会失败?
【问题讨论】:
标签: php laravel validation laravel-5.2