首页 > 解决方案 > 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这样它就不会在自定义验证中失败?

标签: phplaravelvalidationlaravel-5.2

解决方案


您应该首先检查给定值是否有效日期,像这样

if (Carbon::createFromFormat('date format', $date['day']) !== false) {
        // valid date
}

我希望这将有所帮助。


推荐阅读