在 Laravel 中将参数验证为 JSON 字符串

ggd*_*ras 2 php json laravel laravel-5 laravel-validation

前端部分

参数的发送方式如下:

前端发送数据

Laravel 请求

class CarCreateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        //TODO: Define authorization logic, possibly a middleware
        return true;
    }  

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'car.name' => 'present|required'
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

真正的问题

请求类始终验证为 false。我检查了验证数组部分,但看起来这可以发送如下参数:

car[name]=Spidey Mobile
Run Code Online (Sandbox Code Playgroud)

但是,我需要使用 JSON.stringify() 发送字符串化的数据。

有解决方法吗?看起来点符号不起作用,因为这是一个 JSON 字符串而不是数组。我尝试在评估之前修改请求数据,但没有找到任何适用于 Laravel 5.7 的内容。

ggd*_*ras 7

这是解决方案,我在请求中使用了清理和验证器方法,以便在评估之前更改请求数据。

class CarCreateRequest extends FormRequest
{
    /**
    * Determine if the user is authorized to make this request.
    *
    * @return bool
    */
    public function authorize()
    {
        //TODO: Define authorization logic, possibly a middleware
        return true;
    }  

    public function validator($factory)
    {
    return $factory->make(
        $this->sanitize(), $this->container->call([$this, 'rules']), $this->messages()
    );
    }

    public function sanitize()
    {
        $this->merge([
            'car' => json_decode($this->input('car'), true)
        ]);
        return $this->all();
    }

    /**
    * Get the validation rules that apply to the request.
    *
    * @return array
    */
    public function rules()
    {
        return [
            'car.name' => 'present|required'
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

json_decode 会将 JSON 字符串转换为 Laravel 可以验证的数组。


CUG*_*een 5

您应该能够像这样重写请求中的validationData方法:

protected function validationData()
{
    $this->merge(['car', json_decode($this->car)]); // or what ever your request value is.
    return $this->all();
}
Run Code Online (Sandbox Code Playgroud)