【问题标题】:Laravel custom validation check other field provided in parametersLaravel 自定义验证检查参数中提供的其他字段
【发布时间】:2020-07-14 10:15:16
【问题描述】:

除了 required_without 之外,我还想制作自定义验证器,如果所有字段都已填写,也会失败。

现行规则:

'foo' => 'required_without:baz',
'bar' => 'required_without:baz',
'baz' => 'required_without_all:foo,bar',

结果:

  1. Foo、Bar 和 Baz 都是空的(错误)
  2. Foo / Bar 之一已填充,另一个为空(错误)
  3. Foo 和 Bar 已填充,Baz 为空(OK)
  4. Foo 和 Bar 为空,Baz 已填充(OK)
  5. 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.');

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    这就是你想要的

    Validator::extend('empty_if_present', static 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 (! empty(request()->input($param))) {
                $paramsAreEmpty = false;
            }
        }
    
        return $attributeIsNotEmpty && $paramsAreEmpty;
    }, 'The :attribute must be empty if :fields is present.');
    

    【讨论】:

    • 我只是想对编辑发表评论,因为它没有通过我的单元测试,但 foreach 有效
    • 是的,我意识到它会检查这两个字段,所以我之前删除了它
    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2014-12-07
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2021-12-12
    相关资源
    最近更新 更多