Laravel验证数组迭代

时间:2018-05-09 08:31:31

标签: javascript php arrays laravel validation

我通过javascript从我的表单发送了一个数组,它从不同的输入字段中获取值,然后将其存储在单个变量中。

<input type="hidden" name="details" id="details">

JS

document.querySelectorAll('form')[1].addEventListener('submit', function(event) {
    var details = [];
    for (var i = 0; i < {{ $event->grocery->items()->count() }}; i++) {
        details[i] = [
            document.querySelectorAll('.store')[i].value,
            document.querySelectorAll('.item')[i].value,
            document.querySelectorAll('.quantity')[i].value,
            document.querySelectorAll('.brand')[i].value,
            document.querySelectorAll('.size')[i].value,
        ];
    }

    document.querySelector('#details').value = JSON.stringify(details);
});

然后在我的控制器中,我使用json_decode

解码数组
$request->details = json_decode($request->details);

现在,我想验证每次迭代(只是为了检查它是否为空)。所以,我喜欢这个,

$request->validate([
    ...
    'details.*.*' => 'required'
]);

但我的问题是这没有做任何事情。即使我发送了一个空迭代,它也会继续而不会返回错误。

我在这里做错了吗?请帮帮我。

更新

var转储详细信息示例

array:3 [▼
  0 => array:5 [▼
    0 => "Grocery"
    1 => "Grocery"
    2 => "Grocery"
    3 => "Grocery"
    4 => "Grocery"
  ]
  1 => array:5 [▼
    0 => "Grocery"
    1 => "Grocery"
    2 => "Grocery"
    3 => "Grocery"
    4 => "Grocery"
  ]
  2 => array:5 [▼
    0 => "Grocery"
    1 => "Grocery"
    2 => "Grocery"
    3 => "Grocery"
    4 => "Grocery"
  ]
]

1 个答案:

答案 0 :(得分:0)

如果您将数组值命名为

,将会更容易
document.querySelectorAll('form')[1].addEventListener('submit', function(event) {
    var details = [];
    for (var i = 0; i < {{ $event->grocery->items()->count() }}; i++) {
        details[i] = {
            store: document.querySelectorAll('.store')[i].value,
            item: document.querySelectorAll('.item')[i].value,
            quantity: document.querySelectorAll('.quantity')[i].value,
            brand:document.querySelectorAll('.brand')[i].value,
            size: document.querySelectorAll('.size')[i].value,
        };
    }

    document.querySelector('#details').value = JSON.stringify(details);
});

验证将如下所示:

$request->validate([
    ...
    'details.*.store' => 'required',
    'details.*.item' => 'required',
    'details.*.quantity' => 'required',
    'details.*.brand' => 'required',
    'details.*.size' => 'required'
]);

但如果它不适合你,总会有Laravel的Custom Validation Rules

修改

我想可能问题在于您的数据更新:

$request->details = json_decode($request->details);

相反,您应该modify your input befor validationModify input before form request validation

$request->request->set('details', json_decode($request->details));