在后端创建表单中我需要一次验证两个字段(日期),因为我将检查这两个日期之间是否有某个值。
我坚持这个:
我在模型中写道:
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";
});
}
哦,小时搜索和思考,我解决了!
不需要在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.']);
}
}