如何一次验证两个日期

时间:2019-04-21 09:51:48

标签: laravel octobercms

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

我被困在这里:

在我写的模型中:

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

在插件文件中,我写道:

    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";
        });
    }

1 个答案:

答案 0 :(得分: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.']);
    }
}