php - Laravel如何仅在内部数组之间验证不同的规则
问题描述
'variants' => ['nullable', 'array'],
'variants.*.name' => ['required', 'string'],
'variants.*.options' => ['required', 'array', 'min:1'],
'variants.*.options.*.code' => ['required', 'string', 'distinct'],
我在上面有一个验证规则。我想要实现的是仅用于内部数组之间的值的不同,但不知何故我在输入时遇到了这样的错误
输入:
{
variants: [
{
name: "outer array 1",
options: [
{
code: "A"
},
{
code: "B"
}
]
},
{
name: "outer array 2",
options: [
{
code: "A"
},
]
}
]
}
结果:
"error": {
"variants.0.options.0.code": [
"The variants.0.options.0.code field has a duplicate value."
],
"variants.1.options.0.code": [
"The variants.1.options.0.code field has a duplicate value."
]
}
问题:有什么方法可以区分内部数组而不是每个数组?
解决方案
使用自定义验证规则:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Distinct implements Rule
{
protected string $message;
protected string $strict = '';
public function __construct(bool $strict)
{
$this->strict = $strict ? ':strict' : '';
}
/**
* @param string $attribute
* @param array $value
* @return bool
*/
public function passes($attribute, $value)
{
try {
$validation = \Validator::make(['array' => $value], [
'array.*' => ["distinct{$this->strict}"]
]);
$this->message = 'The field has a duplicate value.';
return !$validation->fails();
} catch (\Exception $exception) {
$this->message = "array error";
return false;
}
}
public function message()
{
return $this->message;
}
}
推荐阅读
- excel - 唯一/条件计数公式
- .net-core - 我可以使用 bot 框架作为 MS Teams 中的用户发送/更新消息吗?
- javascript - 我该如何解决这个问题'不允许重复的道具反应/jsx-no-duplicate-props'
- flutter - 如何根据面值对飞镖中的整数列表进行排序?
- python - 用于查找具有非封闭形式解的方程的数值解的 python 包
- typescript - 寻找一种类型安全的方法来压平 pojo
- node.js - React and Express iTunes Search API :: 错误:请求失败,状态码为 404
- javascript - 避免在 Javascript 中使用模板文字
- javascript - 赛普拉斯:如何在页面对象模型中引用其方法之外的别名
- python-3.x - kivy 和 kivymd 中 kivy/波斯语输入的 RTL 输入