簡體   English   中英

Laravel 自定義驗證 json 錯誤消息結構

[英]Laravel customize validate json error message structure

我正在嘗試更改響應的結構以驗證錯誤消息而不是錯誤本身。 Laravel 驗證文檔內容廣泛,但不幸的是,它們只解釋了如何更改特定的錯誤消息。

最終我要做的是從這種格式改變它當我使用它時

  $attr = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|unique:users,email',
        'password' => 'required|string|min:6|confirmed'
    ]);

我明白了

{
"message": "The given data was invalid.",
"errors": {
    "name": [
        "The name field is required."
    ],
    "email": [
        "The email field is required."
    ],
    "password": [
        "The password field is required."
    ]
}

但我試圖得到這樣的東西

{
    "message": "The given data was invalid.",
    "errors": {
        "name": "The name field is required.",
        "email": "The email field is required.",
        "password": "The password field is required."
    }
}

Laravel 錯誤為每個字段返回 Object 的 Arrays 只是因為有時該字段可能有多個錯誤:

例如:

假設您有一個輸入設置為輸入數字“ myNumber ”,例如:

假設我們對“ myNumber ”進行了驗證,假設:

'myNumber' => 'required|numeric|min:6|max:12',

If the user didn't enter a value, then Laravel Validate method will return an Message Object containts ' myNumber ' which is an array of two value the required and the min and max conditions, i think it's clear now, let's go back to your問題:

您可以輕松地在前端訪問errors ,而不是使用 Arrays 的 object 您只能 select 每個數組的第一個索引並將它們組合在一起,如下所示:

{
"message": "The given data was invalid.",
"errors": {
    "name": [
        "The name field is required."
    ],
    "email": [
        "The email field is required."
    ],
    "password": [
        "The password field is required."
    ]
}

//格式化錯誤 OBJECT JS

let FormatedErrors = {

   name = errors.name[0],
   email= errors.email[0],
   password= errors.password[0],
}

現在你會很容易得到你想要的:

{
    "message": "The given data was invalid.",
    "errors": {
        "name": "The name field is required.",
        "email": "The email field is required.",
        "password": "The password field is required."
    }
}

暫無
暫無

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

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