Laravel中表单验证可以用FormRequest来进行,但是这个默认是返回视图文件的,如果想要把验证结果以JSON格式返回,可以使用如下代码(failedValidation函数):
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
class TagStoreRequest 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<string, mixed>
*/
public function rules(): array
{
return [
'tag' => 'required|unique:tags',
];
}
public function messages(): array
{
return [
'tag.required'=> '标签名称不能为空!',
'rag.unique' => '该标签已存在!',
];
}
protected function failedValidation(Validator $validator)
{
throw new ValidationException(
$validator,
response()->json(
[
'code'=>-1,
'msg'=> $validator->errors()->first()
],
Response::HTTP_UNPROCESSABLE_ENTITY
)
);
}
}
本文为“技术点滴”的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。