首页 > 其他 > 详细

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

时间:2021-09-12 13:35:53      阅读:37      评论:0      收藏:0      [点我收藏+]

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!!!‘);
    }

  

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

原文:https://www.cnblogs.com/jinshao/p/15252664.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!