在应用目录下面新建一个validate目录
在目录创建一个BaseValidate文件
继承Thinkphp6的validate层
<?phpnamespace app\api\validate;use app\common\exception\lib\ParameterException;use think\facade\Request;use think\Validate;class BaseValidate extends Validate{public function gocheck(){ //获取http传入的参数$request=Request::instance();$params=$request->param();$result=$this->batch()->check($params);if(!$result){$e=new ParameterException(['msg'=>is_array($this->error) ? implode(';', $this->error) : $this->error,]);throw $e;}else{return true;}}//检测变量是否是正整数数字,protected function isPositiveInteger($value,$rule='',$data='',$field=''){if(is_numeric($value)&&is_int($value +0)&&($value +0)>0){return true;}else{return false;}}//检测变量是否为空值protected function isNotEmpty($value,$rule='',$data='',$field=''){if(empty($value)){return false;}else{return true;}}//检测是否是正确手机号码protected function isMobile($value){$rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';$result = preg_match($rule, $value);if ($result) {return true;} else {return false;}}public function getDataByRule($arrays){if (array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays)) {// 不允许包含user_id或者uid,防止恶意覆盖user_id外键throw new ParameterException(['msg' => '参数中包含有非法的参数名user_id或者uid']);}$newArray = [];foreach ($this->rule as $key => $value) {$newArray[$key] = $arrays[$key];}return $newArray;}}
自定义规则 在目录下的创建一个文件LoginValidate 并且继承BaseValidate
namespace app\api\validate\user;use app\api\validate\BaseValidate;class LoginValidate extends BaseValidate{protected $rule =["phone_number"=>"require|isMobile","password" => "require|",];protected $message =["phone_number"=>'请输入手机号码',"password" =>'请传入密码',];}
在控制层进行使用
use app\api\validate\user\LoginValidate;use app\BaseController;class Login extends BaseController{/** * 登录 * 时间: 2020/7/17 0017 16:43 * @author: marry a wife * @return mixed 登录成功 * @Route("login",method="post") */public function login(){(new LoginValidate())->gocheck();}}
如若没输入phone_number或者password 会返回错误