Laravel:验证 json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44001030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:53:25  来源:igfitidea点击:

Laravel: validate json object

jsonlaravelvalidationlaravel-5.4

提问by MTA

It's the first time i am using validation in laravel. I am trying to apply validation rule on below json object. The json object name is payload and example is given below.

这是我第一次在 laravel 中使用验证。我正在尝试在下面的 json 对象上应用验证规则。json 对象名称是有效负载,示例如下。

payload = {
  "name": "jason123",
  "email": "[email protected]",
  "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"
    }
   ]
}

And the validation code is like below, for testing purpose i am validating name as a digits. When i executed the below code, the above json object is approved and inserted into my database. Instead, it should give me an exception because i am passing name with alpha numeric value, am i doing something wrong:

验证代码如下所示,出于测试目的,我将名称验证为数字。当我执行下面的代码时,上面的 json 对象被批准并插入到我的数据库中。相反,它应该给我一个例外,因为我正在传递带有字母数字值的名称,我做错了什么:

public function store(Request $request)
{

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

回答by Quynh Nguyen

Please try this way

请尝试这种方式

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());
    }
}

digits:value

数字:值

The field under validation must be numeric and must have an exact length of value.

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

回答by Tarek Adam

I see some helpful answers here, just want to add - that my preference is that controller functions only deal with valid requests. So I keep all validation in the request. Laravel injects the request into the controller function after validating all the rules within the request. With one small tweak (or better yet a trait) the standard FormRequest works great for validating json posts.

我在这里看到了一些有用的答案,只是想补充一下 - 我的偏好是控制器功能只处理有效的请求。所以我在请求中保留所有验证。Laravel 在验证请求中的所有规则后将请求注入控制器函数。通过一个小的调整(或者更好的特性),标准的 FormRequest 非常适合验证 json 帖子。

Client example.js

客户端示例.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

项目/路由/api.php

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

app/Http/Requests/MyJsonRequest.php (as generated by php artisan make:request MyJsonRequest)

app/Http/Requests/MyJsonRequest.php(由 生成php artisan make:request MyJsonRequest

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TrafficRequest 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();
    }
}

回答by rchatburn

Your payload should be payload: {then you can do

你的有效载荷应该是payload: {你可以做的

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

or if you are not sending the payload key you can just use $request->all()

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

回答by Chay22

Use the Validatorfactory class instead using validatemethod derived from controller's trait. It accepts array for the payload, so you need to decode it first

使用Validator工厂类而不是使用validate从控制器特征派生的方法。它接受有效载荷的数组,因此您需要先对其进行解码

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