2 回答
TA貢獻1810條經驗 獲得超4個贊
對于復雜的驗證規則
use Illuminate\Support\Facades\Validator;
....
$data = $request->all();
$validator = Validator::make($data,[
//...your unconditional rules goes here
]);
//your conditional rules goes here
$validator->sometimes('active_form', 'before:active_until', function ($request) {
return $request->filled('active_until');//if here return true,rules will apply
});
重要鏈接
TA貢獻1827條經驗 獲得超4個贊
我終于能夠弄清楚了。
這是我的固定代碼:
$validated = $request->validate([
'title' => 'required|string|min:3|max:30|unique:categories',
'description' => 'nullable|string|min:3|max:255',
'active' => 'required|in:yes,no',
'active_from' => 'required_if:active,yes|date',
'active_until' => 'nullable|date|after:active_from',
'highlighted' => 'required_if:active,yes|in:yes,no',
'highlighted_from' => 'required_if:highlighted,yes|date',
'highlighted_until' => 'nullable|date|after:highlighted_from',
]);
即使用戶在活動選擇上選擇“是”,我也不需要檢查兩個日期是可選的,我只需要檢查active_until日期(可選的日期)以查看它是否是active_from日期之后的有效日期。
這樣,即使用戶沒有填寫active_until日期,驗證也不會失敗,因為我在該字段上有可為空的規則。
至于有時規則,據我了解,僅當請求中可能存在或不存在字段時才需要使用它,例如
'active' => 'sometimes|required|in:yes,no',
這樣,僅當它存在于請求中時才需要它,但由于我在我的代碼中使用 required_if,所以它不是必需的,因為它取決于其他字段的值。
- 2 回答
- 0 關注
- 177 瀏覽
添加回答
舉報
