Laravel验证日期范围数组

时间:2018-12-18 15:09:38

标签: laravel laravel-5.7

我在输入中有一个日期范围数组:

[
  [ 'start' => '2000-01-01 00:00:00', 'end' => '2000-01-01 06:00:00' ],
  [ 'start' => '2000-01-02 00:00:00', 'end' => '2000-01-02 12:00:00' ],
  [ 'start' => '2000-01-03 06:00:00', 'end' => '2000-01-03 12:00:00' ],
  [ 'start' => '2000-01-03 05:00:00', 'end' => '2000-01-03 10:00:00' ],
]

所有这些范围必须唯一,并且不能相互交叉。我正在尝试找到一种使用Laravel Validator验证它们的方法。在我的情况下,索引为23的范围是无效的,因为它们彼此交叉

1 个答案:

答案 0 :(得分:2)

在查看了您的要求之后,您必须制定自定义验证规则,如果没有冲突的日期范围,该规则将返回true,否则返回false。

为了实现这种功能,您必须使用以下artisan命令制作自定义验证规则Range。

php artisan make:rule Range

现在,您将在Range.php文件夹中看到App\Rules\

然后使您的代码如下所示。

App \ Rules \ Range.php

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Range implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $intersect = true;
        for($i=0;$i<count($value); $i++){
            for($j=$i+1;$j<count($value); $j++){
                if($value[$i]['start']<=$value[$j]['end'] && $value[$i]['end']>=$value[$j]['start'])
                {
                    $intersect = false;
                }
            }
        }
        return $intersect;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The dates intersect each other.';
    }
}

现在,您可以像这样在验证中使用范围规则,

用法

第一种情况

如果要在控制器中进行验证,

      $this->validate($request,[
          . . .
         'data'=>[new Range],
          . . . 
       ]);

第二种情况

如果您已创建Request类,则

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
            return [
                . . . 
                'data' => [new Range],
                . . .
            ];
}

在这里,数据是发送日期范围的参数。

希望您能理解。如果需要进一步说明,请随时询问。