The following is an introduction to the validator in Thinkphp5 from the thinkphp tutorial column. I hope it will be helpful to friends in need!
The method of using the validator is relatively simple. The main thing is that we need to define the validation rules first. Thinkphp5 stipulates that if we want to use the validator, we need to create the file in the validate folder.
This folder is at the same level as controller and model
We will define the validator under this folder and encapsulate it into a separate class so that it can be used anywhere in the future.
<?php namespace app\admin\validate; use think\Validate; class Add extends Validate{ protected $rule = [ 'name' => 'require', 'phone'=>'require|max:11|min:11|regex:/^1[3-8]{1}[0-9]{9}$/' ]; protected $message = [ 'name.require'=>'用户名必须填写', 'phone.require'=>'请输入手机号码', 'phone.max'=>'手机号码最多不能超过11位', 'phone.min'=>'手机号码不能少于11位', 'phone.regex'=>'手机号码格式不正确', ]; }
We will call this class in the controller to verify the value received in the controller
public function insertUser(Request $request) { $msg = [ "status" => null, 'msg' => null ]; $name = $request->param('name'); $phone = $request->param('phone'); $data = [ 'name' => $name, 'phone' => $phone ]; $addval = new AppAdd(); if (!$addval->check($data)) { $msg['status'] = 0; $msg['msg'] = $addval->getError(); } else{ } }
Use the method to get the instance of the class through new, and then call the check method in this object Validate data
Related recommendations:The latest 10 thinkphp video tutorials
The above is the detailed content of How to use validator in Thinkphp5. For more information, please follow other related articles on the PHP Chinese website!