我有这个帖子:
{
"store_id": "e422ecfe-4061-4cbd-adc2-364122959dac",
"opening_hours": [
{
"id": "a3489e0f-aaf9-44a7-8af7-4225c25cb40e",
"store_id": "e422ecfe-4061-4cbd-adc2-364122959dac",
"day": 1,
"time_slot1_closed": false,
"time_slot1_start": "12:34",
"time_slot1_end": "13:32",
"time_slot2_closed": false,
"time_slot2_start": null,
"time_slot2_end": null,
"comment": "Velit sint ab temporibus praesentium quo vel."
}
]
}
我想验证;time_ slot1_end";在";time_slot1_start";。要做到这一点,我有这样的规则:
return [
'store_id' => 'required|exists:stores,id',
'opening_hours.*.day' => 'required|between:1,7',
'opening_hours.*.time_slot1_start' => 'nullable|date_format:H:i',
'opening_hours.*.time_slot1_end' => 'nullable|date_format:H:i|after:time_slot1_start',
...
];
验证失败。我有这个错误:
{
"message": "The given data was invalid.",
"errors": {
"opening_hours.0.time_slot1_end": [
"The opening_hours.0.time_slot1_end must be a date after time slot1 start."
]
}
}
我尝试了很多组合,都没有成功。我的错误是什么?
您可以编写一个自定义验证规则来检查您喜欢的任何值。我们可以对字符串进行简单的比较,因为它们在早上的时间总是有前导零。
return [
'store_id' => ['required', 'exists:stores,id'],
'opening_hours.*.day' => ['required', 'between:1,7'],
'opening_hours.*.time_slot1_start' => ['nullable', 'date_format:H:i'],
'opening_hours.*.time_slot1_end' => [
'nullable',
'date_format:H:i',
function ($k, $v, $f) {
// get the 0 out of opening_hours.0.time_slot_1_end
$key = explode(".", $k)[1];
if ($v <= $this->opening_hours[$key]["time_slot1_start"])) {
$f("Timeslot $key end must be after start time");
}
},
],
];
它可能是以字符串的形式读取值。在验证之前,请尝试获取时间段的值并将其转换为日期类型。
date('H:i', strtotime(time_slot1_start))
date('H:i', strtotime(time_slot1_end))