除了 required_without 之外,我还想制作自定义验证器,如果所有字段都已填充,则也会失败。
当前规则:
'foo' => 'required_without:baz',
'bar' => 'required_without:baz',
'baz' => 'required_without_all:foo,bar',
将导致:
Foo、Bar、Baz 都是空的(报错)
Foo / Bar 一个被填充,另一个为空(错误)
Foo 和 Bar 已填充,Baz 为空(确定)
Foo 和 Bar 是空的,Baz 是满的 (OK)
Foo Bar 和 Baz 已填充(确定)← 我希望它变成错误
所以我正在使用 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.');
小唯快跑啊