douduan1953
2017-08-14 15:48
浏览 1.1k
已采纳

如何在laravel中验证json数据?

My code to validate data like this :

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'
    ]);
}

The result of echo '<pre>';print_r($request->all());echo '</pre>';die(); like this :

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
)

The data_cache is json data

On the view blade, I add this to display the message validation :

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

If the code executed, there is no display message validation

Seems the validation json data is still wrong

How can I do it correctly?

图片转代码服务由CSDN问答提供 功能建议

我的验证数据的代码如下:

  public function  register(请求$ request)
 {
 // echo'&lt; pre&gt;'; print_r($ request-&gt; all()); echo'&lt; / pre&gt;'; die(); 
 $ this  - &gt;验证($ request,[
'电子邮件'=&gt;'必需',
'密码'=&gt;'必需',
'data_cache.dataCache.id'=&gt;'必需|数字'  
'data_cache.dataCache.quantity'=&gt;'required | numeric'
]); 
} 
   
 
 

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

 <  code> Array 
(
 [data_cache] =&gt; {“dataCache”:{“id”:112,“quantity”:1,“information”:“stamford bridge”,“request_date”:“15-08-  2017 02:30:00“},”已过期“:”2017-08-14T16:30:26.272Z“} 
 [email] =&gt; chelsea@gmail.com 
 [密码] =&gt; 87654321 
  )
   
 
 

data_cache是​​json数据

在视图刀片上,我添加它以显示消息验证:

  @if($ errors-&gt; has('data_cache'))
&lt; span class =“help-block”&gt; 
&lt; strong&gt; {{$ errors-  &gt; first('data_cache')}}&lt; / strong&gt; 
&lt; / span&gt; 
 @ endif 
   
 
 

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

似乎验证json数据仍然存在错误

我该如何正确执行?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqs13465424392 2017-08-14 16:30
    已采纳

    You could try using...

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

    Then continue with the $validate method as you were.

    There is a field which checks whether the data field under validation is a valid json string or not, but that's not what you need.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题