如何在laravel表单验证错误消息中提供自定义字段名称 [英] How to give custom field name in laravel form validation error message

查看:644
本文介绍了如何在laravel表单验证错误消息中提供自定义字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试laravel中的表单验证。
我的表单中有一个名为'Category'的输入文本字段,我给出的字段名称简写为'cat'。

I was trying form validation in laravel. I have a input text field in my form called 'Category' and i'm given the field name as 'cat' as short.

我定义了这样的验证规则。

And i defined the validation rules like this.

public static $rules=array(
         "name"=>"required|min:3",
          "cat"=>"required"
           );

当验证失败时,我得到像这样的错误消息

When the validation fails i'm getting error message like this

The name field is required.
The cat field is required.

但我想将它显示为类别字段是必需的而不是猫。
如何在'错误信息'中将'cat'更改为'Category'?

But i want to display it as "The category field is required" instead of 'cat'.
How can i change 'cat' to 'Category' in error message ?.

推荐答案

消息为您的字段如下。

$messages = array(
    'cat.required' => 'The category field is required.',
);

$validator = Validator::make($input, $rules, $messages);

请参阅 laravel文档中的自定义错误消息部分以获取更多信息。

Please see Custom Error Messages section in laravel documentation for more information.

或者您可以为您的字段名称保留一个映射,如下所示。你可以将这些设置为你的验证器。所以你可以看到描述性的名字,而不是真正的字段名。

Or you can keep a mapping for your field names like below. And you can set those into you validator. So you can see descriptive name instead of real field name.

$attributeNames = array(
   'name' => 'Name',
   'cat' => 'Category',     
);

$validator = Validator::make ( Input::all (), $rules );
$validator->setAttributeNames($attributeNames);

这篇关于如何在laravel表单验证错误消息中提供自定义字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆