我做了一个自定义验证规则,它迭代包含键dates
的对象数组,并检查这些日期是否是连续的(日期之间的差异仅为1天)。为此,我需要填充'day'键并具有正确的日期格式。我将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首先验证'dates.*.day'
必须date_format: Y-m-d
,以便自定义验证不会失败?
答案 0 :(得分:0)
您应首先检查给定值是否有效,如此
if (Carbon::createFromFormat('date format', $date['day']) !== false) {
// valid date
}
我希望这会有所帮助。