Laravel自定义消息以进行阵列验证 [英] Laravel custom messages for array validation
问题描述
我有一个表单,并且有一个视频网址输入字段数组,现在当我验证表单时,如果我有多个带有视频网址的无效字段,则我对每个无效字段都收到相同的消息,因为我做了我自己的自定义消息.我不想为每个输入字段都输入相同的错误消息,也不想为默认的Laravel错误消息提供与错误消息一起显示字段名称的数组,而不是我想要的错误消息值,在这种情况下是用户写的url.该怎么做?
I am having a form and I have an array of input fields for video urls, now when I validate form if I have multiple invalid fields with video urls, I get the same message for each of the invalid field, since I made my own custom messages. I don't want for each input field the same error message and I don't want the default Laravel error messages for arrays where the name of the field is shown with the error message, instead of that, I would like to have error messages with the value, in this case url written from the user. How to do that?
这是我的请求文件,其中包含消息和规则:
This is my request file with messages and rules:
public function messages(){
$messages = [
'title.required' => 'Du må ha tittel.',
'type.required' => 'Du må velge artikkeltype.',
'category.required' => 'Du må velge kategori.',
'summary.required' => 'Du må ha inngress.',
'text.required' => 'Du må ha artikkeltekst.',
'active_url' => 'Du må ha gyldig url.',
];
}
public function rules(){
$rules = [
'external_media.*' => 'active_url',
'title' => 'required',
'type' => 'required',
'category' => 'required',
'summary' => 'required',
'text' => 'required',
//'image' => 'required|image|max:20000',
];
return $rules;
}
更新代码以使问题更清楚
当我有这样的请求文件时:
When I have my request file like this:
public function messages(){
$messages = [
'title.required' => 'Du må ha tittel.',
'type.required' => 'Du må velge artikkeltype.',
'category.required' => 'Du må velge kategori.',
'summary.required' => 'Du må ha inngress.',
'text.required' => 'Du må ha artikkeltekst.',
'external_media.active_url' => 'Du må ha gyldig url.',
];
return $messages;
}
public function rules(){
$rules = [
'external_media.*' => 'active_url',
'title' => 'required',
'type' => 'required',
'category' => 'required',
'summary' => 'required',
'text' => 'required',
//'image' => 'required|image|max:20000',
];
return $rules;
}
我得到输出:
The external_media.0 is not a valid URL.
The external_media.1 is not a valid URL.
The external_media.2 is not a valid URL.
我想获取每种输入的值而不是这种输出,并具有以下内容:
Instead of that kind of output I would like to take the value for each of those inputs and have something like:
The htt:/asdfas.com is not a valid URL.
推荐答案
public function messages() {
$messages = [
'title.required' => 'Du må ha tittel.',
'type.required' => 'Du må velge artikkeltype.',
'category.required' => 'Du må velge kategori.',
'summary.required' => 'Du må ha inngress.',
'text.required' => 'Du må ha artikkeltekst.',
];
foreach ($this->get('external_media') as $key => $val) {
$messages["external_media.$key.active_url"] = "$val is not a valid active url";
}
return $messages;
}
这篇关于Laravel自定义消息以进行阵列验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!