【问题标题】:How to validate two dates at a time如何一次验证两个日期
【发布时间】:2019-09-10 21:29:36
【问题描述】:

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

我被困在这个:

在我写的模型中:

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

【问题讨论】:

    标签: laravel octobercms


    【解决方案1】:

    天哪,几个小时的搜索和思考,我解决了!

    不需要 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.']);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-12
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多