猿问

Laravel 自定义验证检查参数中提供的其他字段

除了 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 为空(确定)

  4. Foo 和 Bar 是空的,Baz 是满的 (OK)

  5. 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.');


墨色风雨
浏览 168回答 1
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.');
随时随地看视频慕课网APP
我要回答