Laravel5.1 框架表单验证操作实例详解(2)

↑ 上面的例子如果验证通过 则显示"验证通过" 如果验证没有通过的话Laravel会自动跳转到表单提交页面 并把错误信息闪存到Session中,我们可以修改create.balde.php文件 添加显示错误代码

2.2 显示错误信息

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" >
</head>
<body>
<div class="container">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">
          创建文章
        </div>
        <div class="panel-body">
          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif
          <form action="{{ url("/post") }}" method="POST" class="form-horizontal">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <div class="form-group">
              <label class="col-md-4 control-label">标题</label>
              <div class="col-md-6">
                <input type="text" class="form-control" name="title">
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label">内容</label>
              <div class="col-md-6">
                <textarea rows="10" class="form-control" name="content"></textarea>
              </div>
            </div>
            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button class="btn btn-primary" type="submit">Submit</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>

3 手动创建Validator

  public function store(Request $request)
  {
//    $this->validate($request, [
//      'title' => 'required|min:3',
//      'content' => 'required|min:10',
//    ]);
    $validator = Validator::make($request->all(), [
      'title' => 'required|min:3',
      'content' => 'required|min:10',
    ]);
    if ($validator->fails()) {
      return redirect('post/create')
        ->withErrors($validator)
        ->withInput();
    }
    echo '验证通过';
  }

更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》