【问题标题】:How can I validate json data in laravel?如何在 laravel 中验证 json 数据?
【发布时间】:2018-01-22 12:23:45
【问题描述】:

我的代码来验证这样的数据:

public function register(Request $request)
{
    //echo '<pre>';print_r($request->all());echo '</pre>';die();
    $this->validate($request, [
        'email'=>'required',
        'password'=>'required',
        'data_cache.dataCache.id'=>'required|numeric'
        'data_cache.dataCache.quantity'=>'required|numeric'
    ]);
}

echo '&lt;pre&gt;';print_r($request-&gt;all());echo '&lt;/pre&gt;';die(); 的结果如下:

Array
(
    [data_cache] => {"dataCache":{"id":112,"quantity":1,"information":"stamford bridge","request_date":"15-08-2017 02:30:00"},"expired":"2017-08-14T16:30:26.272Z"}
    [email] => chelsea@gmail.com
    [password] => 87654321
)

data_cache是​​json数据

在视图刀片上,我添加了这个来显示消息验证:

@if ($errors->has('data_cache'))
    <span class="help-block">
        <strong>{{ $errors->first('data_cache') }}</strong>
    </span>
@endif

如果代码执行,则没有显示消息验证

看来验证json数据还是错的

我怎样才能正确地做到这一点?

【问题讨论】:

    标签: php json laravel validation laravel-5.3


    【解决方案1】:

    您可以尝试使用...

    $dataCache = json_decode($request->data_cache);
    
    $request->merge(['id' => $dataCache.dataCache.id, 'quantity' => $dataCache.dataCache.quantity]);
    

    然后像以前一样继续使用 $validate 方法。

    有一个字段可以检查验证中的数据字段是否是有效的 json 字符串,但这不是您需要的。

    【讨论】:

      猜你喜欢
      • 2019-06-10
      • 2015-01-31
      • 2015-09-01
      • 2017-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2021-10-12
      • 1970-01-01
      相关资源
      最近更新 更多