简体   繁体   English

Laravel - 如何在验证中限制与“in”混合的数组大小?

[英]Laravel - How to limit array size mixed with 'in' in validation?

How to limit array size to have 2 items in it or 4. not min 2 and max 4.如何将数组大小限制为 2 个或 4 个项目。不是最小 2 和最大 4。

$validity = Validator::make($data, [
    'array',
    // 'between:2,4', this will include 3 too. but I need only 2 and 4.
    // 'in:2,4' something like this
]);

You need a custom Rule, probably a Closure like following:您需要一个自定义规则,可能是一个像下面这样的闭包:

https://laravel.com/docs/7.x/validation#using-closures https://laravel.com/docs/7.x/validation#using-closures

function ($attribute, $value, $fail) {
    if (!in_array(count($value), [2, 4])) {
        $fail($attribute.' must have either 2 elements or 4.');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM