如何一次验证两个日期

问题描述 投票:2回答:1

在后端创建表单中我需要一次验证两个字段(日期),因为我将检查这两个日期之间是否有某个值。

我坚持这个:

我在模型中写道:

public $rules = [
    'date_in' => 'checkDate',
    'date_out' => 'checkDate',
];

在Plugin文件中我写道:

    public function boot()
    {
        Validator::extend('checkDate', function($attribute, $value, $parameters) {
                // I need here two dates
                // a rough condition example: $someValue BETWEEN $date1 AND $date2
                if (condition) return false;
        });

        Validator::replacer('checkDate', function ($message, $attribute, $rule, $parameters) {
            return "My error message";
        });
    }
laravel octobercms
1个回答
0
投票

哦,小时搜索和思考,我解决了!

不需要在Plugin.php中使用boot()函数。我只使用beforeSave函数来实现这个目标。它在模型中:

use Db;
use \October\Rain\Exception\ValidationException;
class myModel extends Model
{
    public function beforeSave()
    {
        // I can access dates like that!
        $start = $this->date_in;
        $end = $this->date_out;

        $check = Db::table('mytable')
            ->whereBetween('myColumn', [$start, $end])
            ->get();

        if ($check->count() > 0)
            throw new ValidationException(['date_in' => 'My error message.']);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.