我的livewire表格里面有四張卡片,用戶可以選擇自己想回答的卡片,而且可以多張卡片。所以我做了一個條件來檢查選擇了哪些卡,只驗證資料并根據選擇的卡創建資料庫條目。
CardFormComponent.php:
public function submit()
{
$user = auth()->user();
if($this->showDiv1){
$salary_data = $this->validate([
'emp_name' => 'required',
'emp_length' => 'required',
'emp_monthly_gross_salary' => 'required',
'monthly_allowance' => 'required',
])->validateWithBag('salary_error');
}
if($this->showDiv2){
$gig_data = $this->validate([
'role' => 'required',
'est_earnings' => 'required',
])->validateWithBag('gig_error');
}
if($this->showDiv3){
$self_data = $this->validate([
'business_type' => 'required',
'other_type' => 'required',
'date_com_trade' => 'required',
'no_of_emp' => 'required',
'business_registration_number' => 'required',
'office_ph_no' => 'required',
'share_of_bus' => 'required',
'last_2_year_profit' => 'required'
])->validateWithBag('self_error');
}
if($this->showDiv4){
$investment_data = $this->validate([
'inv_name' => 'required',
'yearly_earning' => 'required',
])->validateWithBag('invest_error');
}
$user->user_current_step = Constant::CURR_STEP_COMMITMENT;
$user->save();
alert('success','Your income are saved.');
return redirect()->route('borrower.landing');
}
因此,此代碼用于保存所有卡片中的用戶輸入,但是,例如,當我選擇兩張卡片并提交一個空表單時,錯誤訊息僅出現在第一張卡片中。單獨測驗時,所有卡都會出現錯誤訊息,因此我確信這不是訊息顯示的問題。我的假設是,一旦第一張卡中的驗證失敗,它會在通過其他回圈之前立即回傳視圖。有什么方法可以防止控制器在完成所有驗證之前回傳視圖?
附加說明,一位前輩建議我為每張卡使用錯誤包,從而解釋代碼中的 validateWithBag('name) ,但從我的研究看來,我只能將一個錯誤包傳遞給視圖?而且 validateWithBag() 似乎也進行了自動重定向。
我的代碼是否有任何方法或任何替代方法可以根據所選卡顯示所有錯誤訊息?
uj5u.com熱心網友回復:
我從我的 Facebook 帖子中得到了這個問題的答案,我想我應該在這里分享。
回答:
是的,Laravel validate() 方法將停止執行代碼并回傳錯誤。您可以嘗試在 if 陳述句的末尾只運行一次 validate(),在每個 if 陳述句中,您應該添加代表 Livewire 模型的規則。
希望這能回答您的問題并幫助您。 關于如何撰寫代碼的螢屏截圖
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488884.html
標籤:拉拉维尔 验证 laravel-8 laravel-livewire 火线
上一篇:Rails上的浮點驗證
