我需要为两个日期字段 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 或设置之前,就会忽略 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',
]);
答案 0 :(得分:2)
我自己解决了这个问题,我添加了 nullable 这个作为魅力的规则。因此,如果该字段不为null,则其他验证规则将取代。
// 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',
]);
答案 1 :(得分:0)
// Validation.
$validator = Validator::make($request->all(), [
'amount' => 'required|numeric',
'arrivalFrom' => 'required_if:arrivalTo,"!="," "|required_with:arrivalTo|date_format:dd/mm/yy|before:arrivalTo',
'arrivalTo' => 'required_if:arrivalFrom,"!="," "|required_with:arrivalFrom|date_format:dd/mm/yy|before:arrivalFrom',
]);
我不确定这一点。由于我从未使用required_if
和required_with
,但您可以尝试一下吗?不确定它是否能解决你的问题。让我知道是否会这样。