gpt4 book ai didi

Laravel 有时会验证数组

转载 作者:行者123 更新时间:2023-12-01 01:43:42 26 4
gpt4 key购买 nike

假设我们有以下表单数据:

{age: 15, father: "John Doe"}

我们希望在验证 father 背后有一些复杂的逻辑。字段基于同一项目的其他数据(对于此示例,我们要验证父亲在年龄 < 18 时是否至少有 5 个字符)。

这可以这样做:
Standard validation rules: ['age': 'required|integer']

$validator->sometimes('father', 'required|min:5', function($data) {
return $data['age'] < 18;
});

现在,我们想用一个项目列表来做同样的事情。所以现在,我们有以下表单数据:
[
{age: 25, },
{age: 15, father: "John Doe"},
{age: 40, },
]

通用验证规则现在看起来像这样:
['items.*.age': 'required|integer']

我现在的问题是轻松表达 sometimes每个项目的规则 father字段将取决于项目的 age field 。
$validator->sometimes('items.*.father', 'required|min:5', function($data) {
// Does not work anymore: return $data['age'] < 18;
// Any way to know which item we are dealing with here?
});

我能想到的一种方法是循环验证器中的项目 after打回来。但这似乎不太优雅:(

最佳答案

无法获取 sometimes()以您需要的方式工作。 sometimes()不会在数组项上“循环”,它会被调用一次。

我想出了一种替代方法,它并不完美,但也许您会发现它很有用。

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
Validator::extend('father_required_if_child', function ($attribute, $value, $parameters, $validator) {

$childValidator = Validator::make($value, [
'age' => 'required|integer'
]);

$childValidator->sometimes('father', 'required|min:5', function($data) {
return is_numeric($data['age']) && $data['age'] < 18;
});

if (!$childValidator->passes()) {
return false;
}

return true;

// Issue: since we are returning a single boolean for three/four validation rules, the error message might
// be too generic.

// We could also ditch $childValidator and use basic PHP logic instead.
});

return [
'items.*' => 'father_required_if_child'
];
}

很想知道如何改进。

关于Laravel 有时会验证数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53555098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com