PHP教程

thinkphp6使用validate验证层

本文主要是介绍thinkphp6使用validate验证层,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

创建验证器基类 app/validate/BaseValidate.php

<?php


namespace app\validate;

use think\Validate;
use app\lib\exception\BaseException;

class BaseValidate extends Validate
{
    public function goCheck($scene = false)
    {
        $params = request()->param();//获取所有参数
        // 开始验证
        $check = $scene ?
            $this->scene($scene)->check($params) :
            $this->check($params);
        if (!$this->check($params)) {
            throw new BaseException([
                'msg' => $this->getError(),
                'code' => 400,
                'statusCode' => 400,
            ]);
        }
        return true;
    }
}

创建自定义验证器 app/validate/CeshiValidate.php

<?php
declare (strict_types = 1);

namespace app\validate;


class CeshiValidate extends BaseValidate
{
    /**
     * 定义验证规则
     * 格式:'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'username' => 'require',
        'email' => 'require|email',
    ];

    /**
     * 定义错误信息
     * 格式:'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'username.require' => '用户名不能为空',
        'email.require' => '邮箱不能为空',
        'email.email' => '邮箱格式不正确',
    ];

    protected $scene = [
        'username'  =>  ['username'],
        'email' => ['email'],
    ];
}

控制器中使用验证器 app/index/controller/Index.php

<?php


namespace app\index\controller;

use app\BaseController;
use think\facade\Request;
use app\lib\exception\BaseException;
use app\validate\CeshiValidate;

class Index extends BaseController
{
    public function index()
    {
//        throw (new BaseException(['code'=>400,'statusCode'=>404,'msg'=>'异常']));
//        return '111';
        $scene = '';
        $scene1 = 'username';
        $scene2 = 'email';

        (new CeshiValidate())->goCheck($scene2);
    }
}

 

这篇关于thinkphp6使用validate验证层的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!