【发布时间】:2020-07-14 10:15:16
【问题描述】:
除了 required_without 之外,我还想制作自定义验证器,如果所有字段都已填写,也会失败。
现行规则:
'foo' => 'required_without:baz',
'bar' => 'required_without:baz',
'baz' => 'required_without_all:foo,bar',
结果:
- Foo、Bar 和 Baz 都是空的(错误)
- Foo / Bar 之一已填充,另一个为空(错误)
- Foo 和 Bar 已填充,Baz 为空(OK)
- Foo 和 Bar 为空,Baz 已填充(OK)
- Foo Bar 和 Baz 已填充(确定)← 我希望这变成错误
所以我正在创建custom validator using extend,并希望像这样使用它:
'foo' => 'required_without:bar|empty_if_present:baz',
'bar' => 'required_without:foo|empty_if_present:baz',
'baz' => 'required_without_all:foo,bar|empty_if_present:foo,bar',
AppServiceProvider.php
Validator::extend('empty_if_present', function ($attribute, $value, $parameters, $validator) {
$attributeIsNotEmpty = !empty($value);
$paramsAreEmpty = true;
foreach ($parameters as $param) {
// how do I check if Foo and Bar are empty??
if ($param is not empty) {
$paramsAreEmpty = false;
}
}
return $attributeIsNotEmpty && $paramsAreEmpty;
}, 'The :attribute must be empty if :fields is present.');
【问题讨论】: