問題描述
有沒有辦法在驗證發生之前修改表單請求類中的輸入字段?
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 在表單請求驗證前修改輸入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!