阅读 102

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

 

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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐