步骤
1、命令创建表单公共验证类定义异常返回格式且只返回一个错误的提示与继承基础验证的表单类
2、路由使用中间件定义返回正确时的数据格式参考”Laravel注册中间件使用-01“篇章
3、use使用表单验证在控制器中验证请求参数
参考文档:
https://learnku.com/docs/laravel/7.x/validation/7467
实现代码
1、命令创建表单公共验证类定义异常返回格式与继承基础验证的表单类
#公共验证类
php artisan make:request \App\Http\Request\Request
#普通验证类,extends继承公共验证
php artisan make:request \App\Http\Request\FormValidate
App\Http\Request\Request.php
<?php
namespace App\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class Request extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
//定义错误验证值只返回一个错误
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
//使用http异常处理类抛出异常
throw new HttpResponseException(response()->json([
'ret' => 422,
'msg' => $validator->errors()->first(),
'data' => []
], 200));
}
}
App\Http\Request\FormValidate.php
<?php
namespace App\Http\Request;
use App\Http\Request\Request;
class FormValidate extends Request
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|min:6',
'date' => 'required|date',
'email' => 'required|email',
];
}
public function messages()
{
return [
'title.required' => '标题不能为空',
'title.min' => '标题最少6个字',
'date.required' => '日期不能为空',
'date.date' => '日期格式错误',
'email.required' => 'email不能为空',
'email.email' => 'email格式错误',
];
}
}
2、路由使用中间件定义返回正确时的数据格式参考”Laravel注册中间件使用-01“篇章
Route::group(['middleware'=>'apiAfter'],function(){
Route::any('formvalidate','IndexController@formValidateApi');
});
3、use使用表单验证在控制器中验证请求参数
# 使用定义的表单验证
use App\Http\Request\FormValidate as FormRequest;
public function formValidateApi(FormRequest $request)
{
$param = $request->post();
return [200, $param];
}
测试结果: