[英]Custom error messages for array input
在我的表單中考慮以下<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
文件中使用它。
通過以下方式我得到了解決方案
在控制器中
$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.
點表示法用於訪問嵌套數組項,但您將其用於數組鍵。 它期望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.']],
],
],
];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.