簡體   English   中英

Laravel 可空驗證規則不起作用

[英]Laravel nullable validation rule not working

我最近升級到 laravel 5.4(從 5.2 開始)以使用可為nullable的驗證規則。

我有一個字段act_post_code ,它可以是integernull 所以我在我的Request class 中提供了以下規則。

 'act_post_code' => 'integer|nullable'

在 Postman 中使用form-data ,我提供了一個 key = act_post_code ,其值 = null

我得到的響應如下:

 { "act_post_code": [ "The act post code must be an integer." ] }

解釋:

不幸的是, nullable似乎只對某些其他驗證有效。

例如: 'act_post_code' => 'nullable|integer'會給你錯誤: "validation.integer"

但是, 'act_post_code' => 'nullable|date'工作正常。

使固定:

作為這些驗證的變通方法,您可以使它們動態化。 例如,在驗證器之前:

$act_post_code_rules = $request->act_post_code? 'integer': '';

然后,在驗證中:

'act_post_code' => $act_post_code_rules

為了驗證可以是 integer 類型或可為空的字段act_post_code ,您可以嘗試以下操作:

  • 在遷移中聲明時,存在act_post_code列的表的Schema聲明列如$table->integer('act_post_code')->nullable();
  • 這可能只是為您驗證'act_post_code' =>'sometimes|nullable|integer'

打開您的遷移文件並將此字段設置為可為空

例如

Schema::create('your_table_name', function (Blueprint $table) { $table->integer('act_post_code ')->nullable(); });

確保它存在於可填充部分的 model 文件中

protected $fillable = ['act_post_code'];

經過一些測試后,我發現只有當我們傳遞的數據確實是 null 數據時,可空規則才有效。
所以在我的測試用例中,我使用這樣的驗證規則:
"counter" => "nullable|numeric"
在刀片文件中,我使用Form::text('counter','')作為元素來輸入我的數據。

然后我將它與幾個測試用例一起使用:

  1. 當我輸入帶有非數字值的counter數據時,它會響應錯誤:
    "the counter must be a number"
  2. 當我輸入帶有數值的counter數據時,它將通過驗證測試。
  3. 當我沒有向counter輸入任何數據時,它將通過驗證測試。

所以我使用dd($request_data)手動檢查數據,或者如果您使用 ajax 只需return $request_data並使用console.log("data")打印它,例如:

 $.ajax({ type:'POST', data:{_token:"{{ csrf_token() }}", counter:$('input[name="counter"]').val() },success:function(data){ console.log(data); } });

並發現當輸入字段被清空時,它將給出null值。

可以死轉儲請求參數並檢查實際值是 null 還是“null”(在字符串中)。 Sometimes when submitting a form via javascript we use FormData() to append data to the form, in those scenarios it may send a null value as in string type "null"

 array:5 [ "firstName" => "Kaustubh" "middleName" => "null" // null as string "lastName" => "Bagwe" "contactNumber" => null // null value "photo" => null "_method" => "PUT" ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM