laravel 验证类使用validate &validator 简单实例

1、在路由web.php上增加

Route::get('test/validator', 'PHPTestController@getValidator');
Route::post('test/validator', 'PHPTestController@postValidator');

2、增加视图view :validator.php

<body>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            @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('test/validator')}}" method="POST">
                <input type="hidden" name="_token" value="{{csrf_token()}}">
                <legend style="text-align: center">表单提交</legend>
                <legend style="text-align: center">Person</legend>
                <label style="margin-left: 50%">Name</label>
                <input type="text" name="name">
                <label style="margin-left: 50%">Age</label>
                <input type="text" name="age">
                <button type="submit" class="btn btn-success">Submit</button>
            </form>
        </div>
    </div>
</div>

<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

3、在控制器上使用validate

class PHPTestController extends Controller
{

    public function getValidator(){

        return view('validator.validator');
    }

    public function postValidator(Request $request){
        $rules = [
            'name'=>'required|max:5',
            'age'=>'min:5|max:20'
        ];
        $message = [
            'name.max'=>'最多5个字符',
            'age.min'=>'最小5岁'
        ];
       $validator = $this->validate($request,$rules,$message);//验证不通则终止后面的代码,输出验收信息

        dd('form post success!!!');//如果前面验证通过则输出这行
    }
}

  如果是ajax请求则使用 validator类

    public function postValidator(Request $request){
        $rules = [
            'name'=>'required|max:5',
            'age'=>'min:5|max:20'
        ];
        $message = [
            'name.max'=>'最多5个字符',
            'age.min'=>'最小5岁'
        ];

       $validator = Validator::make($request->all(),$rules,$message);
       print_r($validator->errors()->all());exit;
        dd('form post success!!!');
    }

  

上一篇:@Validate注解使用原理详解


下一篇:Sawtooth 的网络结构