Laravel 5.1 Modify input before form request validation(Laravel 5.1 在表单请求验证前修改输入)
问题描述
有没有办法在验证发生之前修改表单请求类中的输入字段?
Is there a way to modify input fields inside a form request class before the validation takes place?
我想如下修改一些输入日期字段,但它似乎不起作用.
I want to modify some input date fields as follows but it doesn't seem to work.
当我将 $this->start_dt
输入字段设置为 2016-02-06 12:00:00
和 $this->end_dt
到 2016-02-06 13:00:00
我仍然收到验证错误end_dt 必须在 start_dt 之后".这意味着当您更新 rules()<中的
$this->start_dt
和 $this->end_dt
时,输入请求值不会改变/code> 函数.
When I set $this->start_dt
input field to 2016-02-06 12:00:00
and $this->end_dt
to 2016-02-06 13:00:00
I still get validation error "end_dt must be after start_dt". Which means the input request values aren't getting changed when you update $this->start_dt
and $this->end_dt
inside the rules()
function.
public function rules()
{
if ($this->start_dt){
$this->start_dt = Carbon::createFromFormat('d M Y H:i:s', $this->start_dt . ' ' . $this->start_hr . ':'. $this->start_min . ':00');
}
if ($this->end_dt){
$this->end_dt = Carbon::createFromFormat('d M Y H:i:s', $this->end_dt . ' ' . $this->end_hr . ':'. $this->end_min . ':00');
}
return [
'start_dt' => 'required|date|after:yesterday',
'end_dt' => 'required|date|after:start_dt|before:' . Carbon::parse($this->start_dt)->addDays(30)
];
}
注意: start_dt
和 end_dt
是日期选择器字段,start_hr
、start_min代码> 是下拉字段.因此,我需要通过组合所有字段来创建一个日期时间,以便我可以进行比较.
Note: start_dt
and end_dt
are date picker fields and the start_hr
, start_min
are drop down fields. Hence I need to create a datetime by combining all the fields so that I can compare.
推荐答案
从 Laravel 5.4 开始,您可以覆盖 ValidatesWhenResolvedTrait
的 prepareForValidation
方法来修改任何输入.Laravel 5.1 应该可以实现类似的功能.
As of laravel 5.4 you can override the prepareForValidation
method of the ValidatesWhenResolvedTrait
to modify any input. Something similar should be possible for laravel 5.1.
请求中的示例
/**
* Modify the input values
*
* @return void
*/
protected function prepareForValidation() {
// get the input
$input = array_map('trim', $this->all());
// check newsletter
if (!isset($input['newsletter'])) {
$input['newsletter'] = false;
}
// replace old input with new input
$this->replace($input);
}
这篇关于Laravel 5.1 在表单请求验证前修改输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 5.1 在表单请求验证前修改输入
基础教程推荐
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01