Laravel:验证json对象

wpcxdonn  于 2022-12-14  发布在  其他
关注(0)|答案(6)|浏览(168)

这是我第一次在laravel中使用验证。我尝试在下面的json对象上应用验证规则。json对象名是payload,下面给出了示例。

payload = {
  "name": "jason123",
  "email": "email@xyz.com",
  "password": "password",
  "gender": "male",
  "age": 21,
  "mobile_number": "0322 8075833",
  "company_name": "xyz",
  "verification_status": 0,
  "image_url": "image.png",
  "address": "main address",
  "lattitude": 0,
  "longitude": 0,
  "message": "my message",
  "profession_id": 1,
  "designation_id": 1,
  "skills": [
    {
      "id": 1,
      "custom" : "new custom1"
    }
   ]
}

验证代码如下所示,为了测试目的,我将name作为一个数字进行验证。当我执行下面的代码时,上面的json对象被批准并插入到我的数据库中。相反,它应该给予我一个异常,因为我传递的是带有字母数字值的name,我做错了什么吗:

public function store(Request $request)
{

    $this->validate($request, [
        'name' => 'digits',
        'age' => 'digits',
        ]);
}
0lvr5msh

0lvr5msh1#

这边请

use Validator;

public function store(Request $request)
{
    //$data = $request->all();
    $data = json_decode($request->payload, true);
    $rules = [
        'name' => 'digits:8', //Must be a number and length of value is 8
        'age' => 'digits:8'
    ];

    $validator = Validator::make($data, $rules);
    if ($validator->passes()) {
        //TODO Handle your data
    } else {
        //TODO Handle your error
        dd($validator->errors()->all());
    }
}

位数:值

要验证的字段必须是数字,并且必须具有值的确切长度。

mznpcxlj

mznpcxlj2#

我在这里看到了一些有用的答案,只是想补充一下--我的偏好是控制器函数只处理有效的请求。所以我在请求中保留了所有的验证。Laravel在验证了请求中的所有规则之后将请求注入控制器函数。通过一个小的调整(或者更好的是一个特征),标准的FormRequest对于验证json post非常有效。
客户端example.js

var data = {first: "Joe", last: "Dohn"};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST",'//laravel.test/api/endpoint');
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(JSON.stringify(data));

project/routes/api.php

Route::any('endpoint', function (\App\Http\Requests\MyJsonRequest $request){
    dd($request->all());
});

(由php artisan make:request MyJsonRequest生成)

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MyJsonRequest extends FormRequest{

    public function authorize(){
        return true;//you'll want to secure this
    }

    public function rules(){
        return [
            'first' => 'required',
            'last'  => 'required|max:69',
        ];
    }

    //All normal laravel request/validation stuff until here
    //We want the JSON...
    //so we overload one critical function with SOMETHING LIKE this
    public function all($keys = null){
        if(empty($keys)){
            return parent::json()->all();
        }

        return collect(parent::json()->all())->only($keys)->toArray();
    }
}
s6fujrry

s6fujrry3#

你的有效载荷应该是payload: {,然后你就可以

$this->validate($request->payload, [
    'name' => 'required|digits:5',
    'age' => 'required|digits:5',
    ]);

或者如果您不发送有效负载密钥,则可以使用$request-〉all()

hsvhsicv

hsvhsicv4#

$request->merge([
            'meta_data' => !is_null($request->meta_data) ? json_encode($request->meta_data) : null
        ]);

validator = Validator::make($request->all(), [
      'meta_data' => 'nullable|json'
        ]);
8iwquhpp

8iwquhpp5#

使用Validator工厂类,而不是使用从控制器的特征派生的validate方法。

\Validator::make(json_decode($request->payload, true), [
    'name' => 'digits',
    'age' => 'digits',
]);
ma8fv8wu

ma8fv8wu6#

以@tarek-adam为例,在Laravel 9中它将是:

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MyJsonRequest extends FormRequest{

    public function authorize(){
        return true;//you'll want to secure this
    }

    public function rules(){
        return [
            'first' => 'required',
            'last'  => 'required|max:69',
        ];
    }

    //All normal laravel request/validation stuff until here
    //We want the JSON...
    //so we overload one critical function with SOMETHING LIKE this
    public function validationData()
    {
        if(empty($this->all())){
            $res = [
                'success' => false,
                'message' => 'Check your request',
            ];  

            throw new HttpResponseException(
                response()->json($res, 422)
            );
        }

        return $this->all();
    }
}

相关问题