【发布时间】:2020-05-09 02:30:27
【问题描述】:
我正在尝试验证日期字段,以便 active_from 需要是 active_until 之前的日期,而 active_until 需要是一个日期在 active_from 之后。
这两个字段都被隐藏和禁用,直到用户在名为 active 的选择字段上选择“是”。
当用户选择是时,active_from 出现并成为必需,active_until 也出现,但它是可选的,这就是我的问题,因为只要 >active_until 未填充。
据我了解,如果该字段可能已启用/存在,我应该使用有时规则,该规则仅在该字段存在且已启用时才检查其他验证。例如
'active_from' => 'sometimes|required_if:active,yes|date|before:active_until',
如果一个字段可能会或可能不会被填充,则应该使用可为空规则,但如果该字段可能存在或可能不存在,是否也应该使用它?例如
'active_until' => 'sometimes|nullable|date|after:active_from',
所以我的问题是如何检查 active_from 是否在 active_until 之前,只有当 active 被选择为 Yes > 并且仅当 active_until 被填充时。
我是否正确使用了规则,active_from 应该只使用 sometimes 规则还是也应该使用 nullable 规则?
代码:
$validated = $request->validate([
'title' => 'required|string|min:3|max:30|unique:categories',
'description' => 'nullable|string|min:3|max:255',
'active' => 'required|in:yes,no',
'active_from' => 'sometimes|required_if:active,yes|date|before:active_until',
'active_until' => 'sometimes|nullable|date|after:active_from',
'highlighted' => 'sometimes|required_if:active,yes|in:yes,no',
'highlighted_from' => 'sometimes|required_if:highlighted,yes|date|before:highlighted_until',
'highlighted_until' => 'sometimes|nullable|date|after:highlighted_from',
]);
【问题讨论】:
标签: php laravel date validation nullable