用于数组验证的 Laravel 自定义消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37925592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel custom messages for array validation
提问by Marco
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?
我有一个表单,我有一个视频 url 的输入字段数组,现在当我验证表单时,如果我有多个带有视频 url 的无效字段,我会为每个无效字段收到相同的消息,因为我做了自己的自定义消息。我不希望每个输入字段都有相同的错误消息,我不希望数组的默认 Laravel 错误消息显示字段名称与错误消息,而不是,我想要错误消息使用值,在本例中为用户写入的 url。怎么做?
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;
}
Updated code to make the question clearer
更新代码使问题更清晰
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;
}
I get the output:
我得到输出:
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.
回答by Osama Sayed
To use a custom messages from outside the validation language file, you can use it this way:
要使用来自验证语言文件外部的自定义消息,您可以这样使用它:
$messages = ['username.required' => 'customeError'];
$validator = \Validator::make(
$data,
['username' => 'required'],
messages
);
You can just pass an array of your custom messages as the third parameter as I have used it above. Hope this helps.
您可以将自定义消息数组作为第三个参数传递,就像我在上面使用的那样。希望这可以帮助。
回答by smo0f
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;
}
回答by Pooja JaJal
public function messages()
{
$messages = [];
foreach ($this->request->get('external_media') as $key => $val) {
$messages['external_media.' . $key . '.active_url'] = 'The '.$val .' is not a valid URL.'
}
return $messages;
}
回答by Snigdhadeep
I think this will help you if you are using "name=location[]" this in your view page.
如果您在视图页面中使用“name=location[]”,我认为这会对您有所帮助。
for ($i = 0; $i <= sizeof($location); $i++) {
$this->validate($request,
[
// set the rules
'location.'.$i => 'required',
'contact_no.'.$i => 'required',
'email.'.$i => 'required|email',
],
[
// set your custom error messages here
'location.'.$i.'.'.'required' => 'Contact no. is required',
'contact_no.'.$i.'.'.'required' => 'Contact no. is required',
'email.'.$i.'.'.'required' => 'Email is required',
'email.'.$i.'.'.'email' => 'Please enter valid email address'
]);
}
回答by Andrés Escobar
'external_media.*.required' => 'active_url',
回答by GiangNv
You can using Customizing The Error Format
您可以使用自定义错误格式
protected function formatErrors(Validator $validator)
{
$results = [];
$flag = false;
$messages = $validator->errors()->messages();
foreach ($messages as $key => $value) {
if (!str_contains($key, 'external_media') || !$flag) {
$results[] = $value[0];
}
if (str_contains($key, 'external_media') && !$flag) {
$flag = true;
}
}
return $results;
}
回答by Jhon Didier Sotto
This works fine for me in laravel 5.5
这在 Laravel 5.5 中对我来说很好用
$request->validate([
'files.*' => 'required|mimes:jpeg,png,jpg,gif,pdf,doc|max:10000'
],
[
'files.*.mimes' => 'Los archivos solo pueden estar con formato: jpeg, png, jpg, gif, pdf, doc.',
]
);
回答by Jonathon
Edit with potential solution
使用潜在解决方案进行编辑
After some digging around, I've had a look at the Validator
class and how it is adding it's error messages to see if it has any available placeholders.
经过一番挖掘,我查看了Validator
该类以及它如何添加错误消息以查看它是否有任何可用的占位符。
In the Illuminate\Validation\Validator
the function that I think is run to validate a request is validate
, which runs each of the rules in turn and adds error messages. The piece of code related to adding an error message is this one, at the end of the function:
在Illuminate\Validation\Validator
我认为用于验证请求的函数中validate
,它依次运行每个规则并添加错误消息。与添加错误消息相关的一段代码是这个,在函数的末尾:
$value = $this->getValue($attribute);
$validatable = $this->isValidatable($rule, $attribute, $value);
$method = "validate{$rule}";
if ($validatable && ! $this->$method($attribute, $value, $parameters, $this)) {
$this->addFailure($attribute, $rule, $parameters);
}
As you can see, it's not actually passing the value of the field that was validated through when it's adding a failure, which in turn adds an error message.
正如您所看到的,它实际上并没有传递在添加失败时经过验证的字段的值,这反过来又添加了一条错误消息。
I've managed to get something working to achieve what you're after. If you add these two methods into your base Request
class which is usually at App\Http\Requests\Request
:
我已经设法让一些工作来实现你所追求的。如果将这两个方法添加到Request
通常位于的基类中App\Http\Requests\Request
:
protected function formatErrors(Validator $validator)
{
$errors = parent::formatErrors($validator);
foreach ($errors as $attribute => $eachError) {
foreach ($eachError as $key => $error) {
if (strpos($error, ':value') !== false) {
$errors[$attribute][$key] = str_replace(':value', $this->getValueByAttribute($attribute), $error);
}
}
}
return $errors;
}
protected function getValueByAttribute($attribute)
{
if (($dotPosition = strpos($attribute, '.')) !== false) {
$name = substr($attribute, 0, $dotPosition);
$index = substr($attribute, $dotPosition + 1);
return $this->get($name)[$index];
}
return $this->get($attribute);
}
Then in your validation messages you should be able to put the :value
replacer, which should be replaced with the actual value that was validated, like this:
然后在您的验证消息中,您应该能够放置:value
替换器,该替换器应替换为已验证的实际值,如下所示:
public function messages()
{
return [
'external_media.*.active_url' => 'The URL :value is not valid'
];
}
I've noticed a couple of problems with your code:
我注意到您的代码有几个问题:
- In your
messages
function you've provided a message foractive_url
which is the name of the rule, rather than the name of the field. This should beexternal_media
. - You're not returning the
$messages
variable from yourmessages
function. You need to addreturn $messages;
to the end.
- 在您的
messages
函数中,您提供了一条消息,active_url
该消息是规则名称,而不是字段名称。这应该是external_media
。 - 您没有
$messages
从messages
函数中返回变量。你需要添加return $messages;
到最后。
With regards to your question however, the class in which you write this code is an instance of Illuminate\Http\Request
and you should be able to access the actual values provided to that request when generating your error messages. For example, you could do something like this:
但是,关于您的问题,您编写此代码的类是一个实例,Illuminate\Http\Request
您应该能够在生成错误消息时访问提供给该请求的实际值。例如,您可以执行以下操作:
public function messages()
{
return [
'external_media' => 'The following URL is invalid: ' . $this->get('external_media')
];
}
public function rules()
{
return [
'external_media' => 'active_url'
];
}
Which would include the value provided to external_media
in the error message. Hope this helps.
这将包括external_media
错误消息中提供的值。希望这可以帮助。
回答by ashsam786
You can use as
您可以使用作为
$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.',
];
$validator = Validator::make($data, [
'external_media.*' => 'active_url',
'title' => 'required',
'type' => 'required',
'category' => 'required',
'summary' => 'required',
'text' => 'required',
//'image' => 'required|image|max:20000'
], $messages);
if ($validator->fails()){
// handle validation error
} else {
// no validation error found
}
回答by HARIPRASATH PANNEERSELVAM
Array Validation Try this! It really helps https://riptutorial.com/laravel/example/6353/array-validation
数组验证试试这个!它真的有帮助 https://riptutorial.com/laravel/example/6353/array-validation