![](/img/trans.png)
[英]Laravel 4: Validate start and end date with before and after validation
[英]Laravel: How can I validate two optional date fields using the before and after validation rules
我正在嘗試驗證日期字段,以便active_from需要是active_until之前的日期,而active_until需要是active_from之后的日期。
在用戶在名為active的選擇字段上選擇 Yes 之前,這兩個字段都是隱藏和禁用的。
當用戶選擇 Yes 時, active_from出現並變為必需, active_until也出現但它是可選的,這就是我的問題,因為只要active_until未填充,驗證就會失敗。
據我所知,如果該字段可能會或可能不會啟用/存在,我應該使用有時規則,如果該字段存在並啟用,它只會檢查其他驗證。 例如
'active_from' => 'sometimes|required_if:active,yes|date|before:active_until',
如果某個字段可能會或可能不會被填充,則應使用可為空規則,但如果該字段可能存在或可能不存在,則也應使用它? 例如
'active_until' => 'sometimes|nullable|date|after:active_from',
所以我的問題是,僅當將active選擇為Yes並且僅當active_until被填充時,我才能檢查active_from是否在active_until之前。
我是否正確使用規則, active_from應該只使用有時規則還是也應該使用可為空規則?
代碼:
$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' => 'sometimes|required_if:active,yes|date|before:active_until',
'active_until' => 'sometimes|nullable|date|after:active_from',
'highlighted' => 'sometimes|required_if:active,yes|in:yes,no',
'highlighted_from' => 'sometimes|required_if:highlighted,yes|date|before:highlighted_until',
'highlighted_until' => 'sometimes|nullable|date|after:highlighted_from',
]);
我終於弄清楚了。
這是我的固定代碼:
$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,所以沒有必要,因為它取決於另一個字段的值。
對於復雜的驗證規則
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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.