Laravel 通过(扩展 FormRequest 类)方法验证表单请求

问题描述 投票:0回答:1

我通过创建自己的

UserStoreRequest
类在 Laravel 中实现了表单验证,该类扩展了
FormRequest
类。我正在使用阿贾克斯。顺便说一句,每当验证失败时,Laravel 都会自动创建一个 JSON 响应并将其发送到浏览器,包括验证错误。问题是我需要帮助来拦截它。我读过文档,它说每当遇到错误时,Laravel 都会抛出这个异常:

照亮\Validation\ValidationException。

我的问题是如何拦截 Laravel 自动生成的 JSON 响应并以我自己的方式将内容放入其中。还有出路吗?我可以对

ValidationException
类做任何事情吗?

php ajax laravel laravel-formrequest
1个回答
0
投票

您可以通过重写

failedValidation
类中的
UserStoreRequest
方法来自定义错误响应。当验证失败时调用此方法。默认情况下,它会抛出一个
ValidationException
来生成您所看到的 JSON 响应。

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class UserStoreRequest extends FormRequest
{
    // ...

    protected function failedValidation(Validator $validator)
    {
        $response = response()->json([
            'data' => $validator->errors(),
            'custom_message' => 'Your custom message here',
            // Add more data if needed
        ], 422);

        throw new HttpResponseException($response);
    }
}

在此示例中,当验证失败时,会抛出

HttpResponseException
和自定义 JSON 响应。
422
状态代码通常用于验证错误。请随意根据需要定制响应。

© www.soinside.com 2019 - 2024. All rights reserved.