laravel表单自定义验证提示信息

水一篇 有用的文章
laravel的验证器中,默认的提示信息是英文,但在实际开发中,经常会使用中文的提示信息,尤其是在验证表单输入时。
  由于官方文档写得很是简略,所以当时在使用验证器自定义提示信息时,还是很花了一番功夫,网上也查了一些资料,但都是神龙见首不见尾,因此在此记录下,让初学者少走弯路。
  自定义验证器的内容如下,相信只要有点PHP功底的,都能看懂,看不懂的自己去补PHP基础。

public function store(Request $request)
{
    //定义验证规则,是一个数组
    $rules = [
        'title' => 'required|max:64',
        'content' => 'required|max:500',
        'back_color' => 'required|max:10',
        'user_name' => 'required|max:10',
    ];

    //定义提示信息
    $messages = [
        'title.required' => '留言标题不能为空',
        'content.required' => '留言内容不能为空',
        'back_color.required' => '留言背景颜色不能为空',
        'user_name.required' => '留言者姓名不能为空',
    ];

    //创建验证器
    $validator = Validator::make($request->all(), $rules, $messages);
    if ($validator->fails()) {
        return redirect('/index')
                    ->withErrors($validator)
                    ->withInput();
    }

    $posts = Posts::create($request->all());

    return redirect('/index');

}

    

  虽然定义好了验证消息,但是怎么在模板中使用自定义的验证消息,卡了我很久,看到官方的common.errors中输出验证消息的源代码,修改如下以显示索引信息:

@if (count($errors) > 0)
    
    
Whoops! Something went wrong!

    @foreach ($errors->all() as $k => $error)
  • {{ $k }} => {{ $error }}
  • @endforeach
@endif   发现他是一个索引数组,于是想在表单中直接引用,但是直接使用索引输出会出现问题,使用索引输出的代码如下: $errors->all()[0];//输出第一个提示信息   使用这种方法,直接将提示信息写死了,假设表单中有5条信息,那么就应该有5个验证消息,用户有多少个信息没有填,就会产生多少条提示信息,如果直接使用索引数组下标的方式输出,程序无法判断使用错误提示信息中的哪一个索引。   正确的引用提示消息的代码如下:
{{ csrf_field() }}
@if ($errors->has('title'))

{{ $errors->first('title') }}

@endif
@if ($errors->has('back_color'))

{{ $errors->first('back_color') }}

@endif
@if ($errors->has('user_name'))

{{ $errors->first('user_name') }}

@endif
---------------------

来源:CSDN
原文:https://blog.csdn.net/GorgeousChou/article/details/80275159

你可能感兴趣的:(laravel表单自定义验证提示信息)