如何在Laravel中验证日期数组



下面的start_date和end_date字段验证不通过。

ErrorException:strtotime((要求参数1为字符串、数组给定

public function rules()
{
return [
'location_id.*' => 'required_without_all:user_id,service_id|integer|gt:0',
'service_id.*' => 'required_without_all:user_id,location_id|integer|gt:0',
'user_id.*' => 'required_without_all:location_id,service_id|integer|gt:0',
'start_date.*' => 'required|date|after_or_equal:now',
'end_date.*' => 'nullable|date|after_or_equal:start_date',
'day_name.*' => 'nullable|integer|between:1,7',
'start_time.*' => 'required|date_format:H:i|before:end_time',
'end_time.*' => 'required|date_format:H:i|after:start_time',
'created_by_user_id.*' => 'required|integer|gt:0',
];
}
protected function prepareForValidation()
{
$row = count($this->day_name);
$this->merge([
'location_id' => array_fill(0, $row, $this->location_id),
'service_id' => array_fill(0, $row, $this->service_id),
'user_id' => array_fill(0, $row, $this->user_id),
'start_date' => array_fill(0, $row, Carbon::parse($this->start_date)),
'end_date' => array_fill(0, $row, Carbon::parse($this->end_date)),
'day_name' => array_fill(0, $row, $this->day_name),
'start_time' => array_fill(0, $row, $this->start_time),
'end_time' => array_fill(0, $row, $this->end_time),
'created_by_user_id' => array_fill(0, 3, $this->created_by_user_id),
]);

start_date是一个碳实例,如下所示:

dd($this->start_date)); // In the start of public function rules()
array:3 [
0 => CarbonCarbon @1587484783^ {#1470
#constructedObjectId: "000000006789d240000000000f12e56f"
#localMonthsOverflow: null
#localYearsOverflow: null
#localStrictModeEnabled: null
#localHumanDiffOptions: null
#localToStringFormat: null
#localSerializer: null
#localMacros: null
#localGenericMacros: null
#localFormatFunction: null
#localTranslator: null
#dumpProperties: array:3 [
0 => "date"
1 => "timezone_type"
2 => "timezone"
]
#dumpLocale: null
date: 2020-04-21 15:59:43.430962 UTC (+00:00)
timezone: "UTC"
}
1 => CarbonCarbon @1587484783^ {#1470}
2 => CarbonCarbon @1587484783^ {#1470}
]

所有字段都属于同一个表。有些是非数组,有些是数组输入。因此,将它们全部转换为数组,以执行多个记录插入。

您遇到的问题是,您正在传递一个日期数组,以便与每个"start_date"或每个"end_date"进行比较。使用Laravel现有的验证规则,您能够验证这一点的唯一方法是更改请求的形成方式。

而不是将其传递给您的请求:

{
start_date: ['YYYY-MM-DD', 'YYYY-MM-DD', 'YYYY-MM-DD'],
end_date: ['YYYY-MM-DD', 'YYYY-MM-DD', 'YYYY-MM-DD']
}

试着传递这个:

{
dates: [
{start_date: 'YYYY-MM-DD', end_date: 'YYYY-MM-DD'},
{start_date: 'YYYY-MM-DD', end_date: 'YYYY-MM-DD'},
{start_date: 'YYYY-MM-DD', end_date: 'YYYY-MM-DD'}
]
}

使用此语法,您可以验证每个"start_date"及其相应的"end_date",反之亦然:

public function rules()
{
return [
'dates.*.start_date' => 'required|date|after_or_equal:now',
'dates.*.end_date' => 'nullable|date|after_or_equal:start_date'
];
}

相关内容

  • 没有找到相关文章

最新更新