Laravel:验证JSON对象 [英] Laravel: validate json object
问题描述
这是我第一次在laravel中使用验证.我正在尝试对以下json对象应用验证规则. json对象名称是有效负载,下面给出示例.
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.
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对象被批准并插入到我的数据库中.相反,它应该给我一个例外,因为我正在传递带有字母数字值的名称,这是我做错了什么:
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:
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());
}
}
digits:value
正在验证的字段必须为数字,并且必须具有确切的值长度.
digits:value
The field under validation must be numeric and must have an exact length of value.
这篇关于Laravel:验证JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!