我有一个像我这样的JSON结构,我想验证它。
{
"result":[{
"product_id": 1,
"client": 49,
"ticket": 2,
"sold_from_date": 1431588871,
"sold_to_date": 1433122200,
"discount_given":18,
"cheques":[{
"cheque_number" : 123456,
"amount": 6000,
"cheque_date": 1433122200,
"bank": "UCD"
},
{"cheque_number" : 456234,
"amount": 6000,
"cheque_date": 1433122200,
"bank": "AMB"
}
]
},
{
"product_id": 1,
"client": 49,
"ticket": 2,
"sold_from_date": 1433122200,
"sold_to_date": 1434688959
}]
}
我想在Laravel中验证这个JSON。
我试过这样做:
$validator = \Validator::make($data, []);
$validator->each('result.product_id' , ['required|numeric']);
$validator->each('result.sold_from_date' , ['required|numeric']);
$validator->each('result.sold_to_date' , ['required|numeric']);
$validator->each('result.cheques.cheque_number' , ['sometimes|required|numeric']);
$validator->each('result.cheques.amount', ['sometimes|required|numeric']);
return $validator;
我每次都会收到此错误:
每个()的属性必须是一个数组。
另外,我如何验证支票?因为它可以或不可以在JSON中。
答案 0 :(得分:0)
使用array
功能从json
创建json_decode
。
尝试:
$dataarray = json_decode($data);
$validator = \Validator::make($dataarray['result'][0], [
'product_id' => 'required|numeric',
'sold_from_date' => 'required|numeric'
]);
迭代数组:
$roles = array(
'product_id' => 'required|numeric',
'sold_from_date' => 'required|numeric'
);
foreach($data as $element)
{
foreach($element as $value) {
$validator = \Validator::make($value, $roles);
}
}