[英]Laravel: Custom validation messages in Custom Form Requests
我試圖保持控制器整潔,並將自定義請求驗證移至一個單獨的類中,如下所示:
public function register(RegisterUserRequest $request)
並在其中定義所有常用功能,例如
public function rules(),
public function messages(), and
public function authorize()
但是,前端希望顯示以下數據: title
(與驗證錯誤消息相關的標題), description
(這是實際的驗證錯誤消息)和status
(=紅色,黃色等)
我實際上如何自定義請求的響應?
像這樣的東西似乎不起作用:
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
$response = new Response(['data' => [],
'meta' => [
'title' => 'Email Invalid'
'description' => '(The error message as being returned right now)',
'status' => 'red'
]);
throw new ValidationException($validator, $response);
}
有任何想法嗎?
您可以通過在laravel中進行如下請求來做到這一點:
php artisan make:request FailedValidationRequest
該命令將在以下目錄中創建名為FailedValidationRequest的類
App \\ Http \\ Request目錄,然后您可以在此類中編寫規則,如下所示:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class FailedValidationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required'
'description' => 'required',
'status' => 'required|numeric'
];
}
}
如果要自定義錯誤消息,則可以使用composer從此鏈接下載所需的語言: https : //packagist.org/packages/caouecs/laravel-lang
並通過將語言版本復制到資源文件夾中的lang目錄中來編寫所需的語言。
'custom' => [
'title' => [
'required' => 'your custom message goes here',
],
'decription' => [
'required' => 'your custom message goes here',
],
],
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.