在我的表单中考虑以下<input>
数组:
<input type="text" name="title[1]" value="">
<input type="text" name="title[2]" value="">
<input type="text" name="title[3]" value="">
数字( 1,2,3 )指的是不同的语言。 1 =英语,2 =德语等
如何为输入数组添加自定义错误消息?
我在app/lang/en/validation.php
:
<?php
return [
'custom' => [
'title.1' => [
'required' => 'The english title is required.',
],
'title.2' => [
'required' => 'The german title is required.',
],
'title.3' => [
'required' => 'The italian title is required.',
],
],
];
?>
Laravel抛出默认错误消息,而不是使用我的自定义消息:
title.1字段是必需的。
title.2字段是必需的。
title.3字段是必需的。
感谢您提供任何帮助!
编辑:如果我将消息传递给我的验证器,就可以了:
$messages = array(
'title.1.required' => 'The english title is required',
);
$validator = Validator::make($data = Input::all(), $rules, $messages);
但我无法在app/lang/en/validation.php
文件中使用它。
答案 0 :(得分:1)
通过使用以下方式我得到溶液
在控制器中
$input=array (
'name' => 'pro 1',
'barcode' => '2222',
'vendors' =>
array (
0 =>
array (
'id' => 51,
'name' => 'v1',
'item_code' => 'khgjhgjhkhjgjhgjhkhjgjhgjhkhjgjhgjhvv',
),
1 =>
array (
'id' => 43,
'name' => 'v3',
'item_code' => 'aerfaf132aw1d32aw1d32wad',
),
),
)
$validation = Product::validate($input);
if ($validation != null && $validation != "" && $validation->fails()) {
$breakline = $validation->messages()->all();
$message = implode("<br> ", $breakline);
Log::warning('Admin::ProductsController::store::' . $message);
return Response()->json('', $message));
}
在模型中
public static function validate($data) {
$rule = array(
'name' => 'required|max:255',
'barcode' => 'required|max:255',
'vendors'=>'present|array|size:1,5',
'vendors.*.item_code' => 'max:6'
);
$messages = array(
'required' => ':attribute field is required.',
'name.max' => ':attribute may not be greater than :max characters.',
'barcode.max'=>':attribute may not be greater than :max characters.'
'size'=>'only allowed one to five vendor.',
);
$data = Validator::make($data, $rule, $messages);
$data->setAttributeNames(array(
'name' => ucfirst('name'),
'barcode' => ucfirst('barcode'),
'vendors.*.item_code' => ucfirst('item code'),
));
return $data;
}
它将显示
Item code may not be greater than 6.
Item code may not be greater than 6.
答案 1 :(得分:0)
点表示法用于访问嵌套数组项,但您将其用于数组键。它期望title
和1
是彼此嵌套的两个不同的数组键。这可能是您的自定义错误消息不匹配的原因。相反,试试这个:
return [
'custom' => [
'title' => [
[ 1 => ['required' => 'The english title is required.']],
[ 2 => ['required' => 'The german title is required.' ]],
[ 3 => ['required' => 'The italian title is required.']],
],
],
];