Laravel 数组键验证

问题描述 投票:0回答:3

我有自定义请求数据:

{
    "data": {
        "checkThisKeyForExists": [
            {
                "value": "Array key Validation"
            }
        ]
    }
}

这个验证规则:

$rules = [
    'data' => ['required','array'],
    'data.*' => ['exists:table,id']
];

如何使用 Laravel 验证数组键?

laravel validation
3个回答
4
投票

正确的方法
这在 Laravel 中是不可能的,但您可以添加新的验证规则来验证数组键:

php artisan make:rule KeysIn

规则应大致如下所示:

class KeysIn implements Rule
{
    public function __construct(protected array $values)
    {
    }

    public function message(): string
    {
        return ':attribute contains invalid fields';
    }

    public function passes($attribute, $value): bool
    {
        // Swap keys with their values in our field list, so we
        // get ['foo' => 0, 'bar' => 1] instead of ['foo', 'bar']
        $allowedKeys = array_flip($this->values);

        // Compare the value's array *keys* with the flipped fields
        $unknownKeys = array_diff_key($value, $allowedKeys);

        // The validation only passes if there are no unknown keys
        return count($unknownKeys) === 0;
    }
}

你可以像这样使用这个规则:

$rules = [
    'data' => ['required','array', new KeysIn(['foo', 'bar'])],
    'data.*' => ['exists:table,id']
];

快速方法
如果您只需要执行一次,您也可以用快速而肮脏的方式来完成:

$rules = [
    'data' => [
        'required',
        'array',
        fn(attribute, $value, $fail) => count(array_diff_key($value, $array_flip([
            'foo',
            'bar'
        ]))) > 0 ? $fail("{$attribute} contains invalid fields") : null
    ],
    'data.*' => ['exists:table,id']
];

3
投票

也许对你有帮助

$rules = ([
    'name' => 'required|string',    //your field
    'children.*.name' => 'required|string',    //your 1st nested field
    'children.*.children.*.name' => 'required|string'    //your 2nd nested field
]);

0
投票

我想这就是你正在寻找的:

$rules = [
   'data.checkThisKeyForExists.value' => ['exists:table,id']
];
© www.soinside.com 2019 - 2024. All rights reserved.