Laravel 中可空和大于条件的日期验证

Son*_*ona 1 laravel laravel-validation laravel-9

我陷入 Laravel 验证中。

$validatedData = $this->validate($request, [
   "date1" => "nullable",
   'date2' => 'nullable|after:date1',
]);
Run Code Online (Sandbox Code Playgroud)

有时,两者都是date1并且date2将会是nullable。如果我选择date2,则date1不能为 null,并且 date 2 应大于 date1。

TIA

OMi*_*hah 5

您可以使用required_with规则根据字段 Y 验证字段 X 是否为必填字段。

用法:required_with:field1,field2,...至少需要 1 个字段。其中field1可以是您要用来检查字段的任何输入参数。

更新的代码:

$validatedData = $this->validate($request, [
  'date1' => 'nullable|date|required_with:date2',
  'date2' => 'nullable|date|after:date1'
]);
Run Code Online (Sandbox Code Playgroud)

解释:

如果该字段具有某些值并且根据传递给它的验证规则成功验证,则此处输入字段date1将是必需的。date2