In Laravel 9, verify that two time fields span cannot exceed 3 months
1. The request parameters are as follows, you need to ensure that the shipping_at_gmt_end cannot exceed the shipping_at_gmt_start for 3 months. as shown in Figure 1
{
"filter": {
"shipping_at_gmt_start": "2024-02-08T16:00:00.000Z",
"shipping_at_gmt_end": "2025-02-08T17:00:00.000Z"
}
}
2. Use closure to customize the verification rules, based on Carbon. After adding SHIPPING_AT_GMT_START for 3 months before comparing with SHIPPING_AT_GMT_END, if SHIPPING_AT_GMT_END is still later than Shipping_at_gmt_start adds the value after 3 months, and the verification fails.
'filter.shipping_at_gmt_start' => 'date',
'filter.shipping_at_gmt_end' => [
'date',
'after_or_equal:filter.shipping_at_gmt_start',
function ($attribute, $value, $fail) use ($params) {
$startDate = Carbon::parse($params['filter']['shipping_at_gmt_start'])->addMonths(3);
$endDate = Carbon::parse($value);
if ($endDate->isAfter($startDate)) {
$fail('交运时间结束与交运时间开始的跨度不可超过3个月');
}
},
],
3. When the Shipping_AT_GMT_START does not exist, the error is reported: undefined array key \”Shipping_at_gmt_start\”, if SHIPPING_AT_GMT_START does not exist, then SHIPPING_AT_GMT_END is not validated. as shown in Figure 2
'filter.shipping_at_gmt_start' => 'date',
'filter.shipping_at_gmt_end' => [
// 如果交运时间开始不存在,则不验证,防止报错:Undefined array key "shipping_at_gmt_start"
'exclude_without:filter.shipping_at_gmt_start',
'date',
'after_or_equal:filter.shipping_at_gmt_start',
function ($attribute, $value, $fail) use ($params) {
$startDate = Carbon::parse($params['filter']['shipping_at_gmt_start'])->addMonths(3);
$endDate = Carbon::parse($value);
if ($endDate->isAfter($startDate)) {
$fail('交运时间结束与交运时间开始的跨度不可超过3个月');
}
},
],
4. When “SHIPPING_AT_GMT_START”: “2024-01-31T16:00:00.000Z”, “Shipping_at_gmt_end”: “2024-05-01t16:00:00.000z” The verification is successful. When “SHIPPING_AT_GMT_START”: “2024-01-31T16:00:00.000Z”, “Shipping_at_GMT_END”: “2024-05-01T16:01:00.000z” Validation failed. in line with expectations. 2024-01-31 After adding 3 months, its value is 2024-05-01, because 2024-04 is only 30 days. Figure 3, Figure 4



