如何编写JSON Laravel的验证规则? [英] How to write validation rule for JSON laravel?
本文介绍了如何编写JSON Laravel的验证规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个我要验证的JSON对象:
There is JSON object that I want to validate:
[{
"id": 1,
"settings": {
"GRSYSEM": 1
}
},
{
"id": 2,
"settings": {
"GRSYSEM": 1
}
},
{
"id": 3,
"settings": {
"GRSYSEM": 1
}
}
]
如何在Laravel中编写验证规则?
How to write validation rule in Laravel?
我尝试了以下规则:
$validator = Validator::make($request->all(), [
'id' => 'required|array',
'id.*' => 'required',
'settings.*.GRSYSEM' => 'required'
]);
推荐答案
您快到了,只需将通配符*
放在第一位即可.
You are almost there, simply put the wildcard *
first:
$validator = Validator::make($request->all(), [
'*.id' => 'required',
'*.settings.GRSYSEM' => 'required'
]);
它的字面意思是:对于数组中的每个元素,我期望一个id
和一个设置GRSYSEM
.
It literally says: For each element in the array, I expect an id
and a setting GRSYSEM
.
您还可以通过使用一些技巧来确保它是一个数组:
You could also ensure it's an array by using a little hack:
$data = ['input' => $request->all()];
$validator = Validator::make($data, [
'input' => 'required|array',
'input.*.id' => 'required',
'input.*.settings.GRSYSEM' => 'required'
]);
这篇关于如何编写JSON Laravel的验证规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文