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

时间:2018-10-23 09:03:37

标签: arrays laravel validation laravel-5.7

我有自定义验证代码:

$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."

如何将我的验证消息替换为阵列项目的单个消息?

1 个答案:

答案 0 :(得分:2)

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

$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