Laravel:验证JSON对象

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

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"

}

]

}

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

public function store(Request $request)

{

$this->validate($request, [

'name' => 'digits',

'age' => 'digits',

]);

}

回答:

请这样

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

}

}

位数:值

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

以上是 Laravel:验证JSON对象 的全部内容, 来源链接: utcz.com/qa/429859.html

回到顶部