亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel:如何使用驗證規則之前和之后驗證兩個可選日期字段

Laravel:如何使用驗證規則之前和之后驗證兩個可選日期字段

PHP
長風秋雁 2022-07-29 10:41:18
我正在嘗試驗證日期字段,以便active_from需要是 active_until 之前的日期,而active_until需要是active_from之后的日期。這兩個字段都被隱藏和禁用,直到用戶在名為active的選擇字段上選擇 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_from是否在active_until之前,只有當active被選擇為Yes并且只有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',]);
查看完整描述

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

    }); 

重要鏈接

條件添加規則
檢索輸入

查看完整回答
反對 回復 2022-07-29
?
GCT1015

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,所以它不是必需的,因為它取決于其他字段的值。


查看完整回答
反對 回復 2022-07-29
  • 2 回答
  • 0 關注
  • 177 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號