首页 > Web开发 > 详细

thinkphp6使用validate验证层

时间:2021-06-18 11:58:51      阅读:17      评论:0      收藏:0      [点我收藏+]

创建验证器基类 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验证层

原文:https://www.cnblogs.com/twilight-sparkle/p/14898445.html

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