laravel-验证器的使用
1.这里只是演示一下基本的验证规则
blade用户登陆模板index.blade.php
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>个人测试网页</title> </head> <body> @if(count($errors)>0) <div class="alert-danger"> <ul> @foreach($errors->all() as $error) <li>{{$error}}</li> @endforeach </ul> </div> @endif <form action="{{url('validate')}}" method="post"> {{csrf_field()}} USERNAME:<input type="text" name="username" ><br> PASSWORD:<input type="password" name="password"><br> <input type="submit" value="提交"> </form> </body> </html>
2.路由
<?php use Illuminate\Support\Facades\Routete; Route::get('index',function (){ return view('index'); }); Route::post('validate','ValidateController@index');
3.控制器中代码(标记的地方也是可以使用的)
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ValidateController extends Controller { // public static $requet; public function __construct(Request $request) { self::$requet=$request; } public function index(){ $rules=['username'=>'required','password'=>'required'];//验证信息 $message=['username.required'=>'姓名不能为空','password.required'=>'密码不能为空'];//自定义验证中文信息 // $data=$this->validate(self::$requet,$rules,$message); $data= \Validator::make(self::$requet->except('_token'),$rules,$message); if ($data->fails()){ return redirect('index')->withErrors($data)->withInput();//传统提交表单 页面会刷新,输入框里的内容会丢失掉。//跟old使用 } } }
4.最终视图