【发布时间】:2018-09-05 14:52:20
【问题描述】:
我需要为 arrivalFrom 和 arrivalTo 两个日期字段设置验证规则。这些字段是可选的,但如果其中一个字段存在,则另一个字段是必需的,并且应该遵循特定的格式。
// Validation.
$validator = Validator::make($request->all(), [
'amount' => 'required|numeric',
'arrivalFrom' => 'required_with:arrivalTo|date_format:dd/mm/yy|before:arrivalTo',
'arrivalTo' => 'required_with:arrivalFrom|date_format:dd/mm/yy|before:arrivalFrom',
]);
如果唯一的规则集是“required_with”,则验证有效,但一旦设置了 date_format 或 before,required_with 就会被忽略.
Validation Message
Please not that neither of the fields "arrivalFrom" / "arrivalTo" are set.
The arrival from does not match the format dd/mm/yy.
The arrival from must be a date before arrival to.
The arrival to does not match the format dd/mm/yy.
The arrival to must be a date before arrival to.
有没有办法一次性完成这些验证,而不是检查输入是否存在,然后设置验证规则。
我正在使用 Laravel 5.4。
编辑:解决方案
// Validation.
$validator = Validator::make($request->all(), [
'amount' => 'required|numeric',
'arrivalFrom' => 'required_with:arrivalTo|nullable|date_format:d/m/y|before:arrivalTo',
'arrivalTo' => 'required_with:arrivalFrom|nullable|date_format:d/m/y|after:arrivalFrom',
]);
【问题讨论】:
标签: php laravel validation