在 Laravel 中验证数组时,如何使用数组项规则添加验证自定义消息?

How to add validation custom messages with array items rules when validating array in Laravel?

我有自定义验证码:

$this->validate($request, [
    'array' => 'required|array|max:100',
    'array.*' => 'required|string|distinct|min:3'
], [
    'array.max' => 'Array can't have more :max items',
]);

如何使用数组项规则添加自定义消息?

例如:'array.item.min' => 'Array items length can't be greater :min charackters'

示例 laravel 数组项的默认验证错误消息:

{
  message: "The given data was invalid."
}

errors: {
  array.3: ["The array.3 must be at least 3 characters."]
}

array.3: ["The array.3 must be at least 3 characters."]

0: "The array.3 must be at least 3 characters."
message: "The given data was invalid."

如何用数组项的单个消息替换此验证消息?

您可以尝试在提交表单时在每个元素上添加自定义消息。这是示例代码

$customMessages['array.max'] = 'Array can't have more :max items';

foreach ($request->get('array') as $key => $value) {
    $customMessages['array.' . $key . '.min'] = 'Array items length can't be greater :min charackters';
}

$this->validate($request, [
    'array' => 'required|array|max:100',
    'array.*' => 'required|string|distinct|min:3'
], $customMessages);

如果你想在你的视图中显示错误,你可以这样做:

@if ($errors->has('array.0'))
    {{ $errors->first('array.0') }}
@endif

如果视图中有 foreach

@if ($errors->has('array.'.$index))
    {{ $errors->first('array.'.$index) }}
@endif