在Laravel的数组规则验证错误消息中指出不正确的键

zbwhf8kr  于 2023-06-24  发布在  其他
关注(0)|答案(2)|浏览(87)

我正在进行FormRequest验证。我使用array规则来确保在验证的数组中只允许指定的键。例如:

$rules = [
  'example' => ['array:something,another'],
];

然而,如果这个规则遇到一个不在白名单中的数组键,我得到的错误消息不是很有描述性:
The :attribute field must be an array.
此消息根本没有引用不正确的数组键,这使得最终用户很难找出他们做错了什么。
我能否改进此错误消息,使其突出显示传递了不正确的密钥?类似于自定义验证消息:
The :key key is not valid for the :attribute field.
我本以为这是以前被问过的,但我的谷歌-fu今天显然不强!谢谢

xkftehaa

xkftehaa1#

一个选项是返回一个自定义验证错误消息,该消息突出显示该特定字段属性和规则所需的键。由于这是一个表单请求,您可以这样做:

class MyRequest extends FormRequest
{
    public function messages(): array
    {
        return [
            'example.array' => 'The :attribute field must be an array with keys something and/or another.',
        ];
    }
}

这不是很好,因为它没有告诉用户错误是什么(是字段不是数组,还是他们的键是错误的,是哪个键?)。它还要求对消息进行硬编码。

nx7onnlm

nx7onnlm2#

一个更好的解决方案是自定义验证规则,它的行为类似于普通的array规则,但给出了更合理的错误消息。
像这样使用它:

use App\Rules\ArrayWith;

$rules = [new ArrayWith('something,another')];

规则本身看起来像:

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class ArrayWith implements ValidationRule
{
    public array $keys;

    public function __construct(string $keys)
    {
        $this->keys = explode(',', $keys);
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!is_array($value)) {
            $fail('The '.$attribute.' field must be an array.');
        }
        foreach (array_keys($value) as $key) {
            if (!in_array($key, $this->keys)) {
                $fail('The '.$key.' key is not valid for the '.$attribute.' field.');
            }
        }
    }
}

老实说,这不是默认行为,这仍然让人感到惊讶。

相关问题