thinkphp6: 用validate验证参数合法性(thinkphp 6.0.9/php 8.0.14)

一,代码:创建两个validate

1,验证商品列表
创建一个validate
liuhongdi@lhdpc:/data/php/admapi$ php think make:validate GoodsList
Validate:app\validate\GoodsList created successfully.
validate/GoodsList.php
<?php
declare (strict_types = 1);
 
namespace app\validate;
 
use think\Validate;
 
class GoodsList extends Validate
{
    /**
     * 定义验证规则
     * 格式:'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'categoryId'  => 'require|integer|gt:0',
        'channelId'  => 'require|length:4|alphaNum',
    ];
 
    /**
     * 定义错误信息
     * 格式:'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'categoryId.require' => '分类id必须',
        'categoryId.integer'     => '分类id需要是整数',
        'categoryId.gt'     => '分类id需大于0',
        'channelId.require' => '频道id必须',
        'channelId.length'     => '频道id长度不为4',
        'channelId.alphaNum'     => '频道id需由字母和数字构成',
    ];
}
2,验证登录
创建validate
liuhongdi@lhdpc:/data/php/admapi$ php think make:validate Login
Validate:app\validate\Login created successfully.
validate/Login.php
<?php
declare (strict_types = 1);
 
namespace app\validate;
 
use think\Validate;
 
class Login extends Validate
{
    /**
     * 定义验证规则
     * 格式:'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'username'  => 'require|min:6|max:25',
        'password'  => 'require|min:6|max:10',
    ];
 
    /**
     * 定义错误信息
     * 格式:'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'username.require' => '用户名必须',
        'username.min'     => '用户名最少不能低于6个字符',
        'username.max'     => '用户名最多不能超过25个字符',
        'password.require' => '密码必须',
        'password.min'     => '密码最少不能低于6个字符',
        'password.max'     => '密码最多不能超过25个字符',
    ];
}

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

 

二,代码:创建一个controller

1,创建controller

liuhongdi@lhdpc:/data/php/admapi$ php think make:controller Auth
Controller:app\controller\Auth created successfully.
代码:
<?php
declare (strict_types = 1);
 
namespace app\controller;
 
use think\Request;
use app\result\Result;
use think\response\Json;
use app\validate\Login as LoginValidate;
use app\validate\GoodsList as GoodsListValidate;
use think\exception\ValidateException;
 
class Auth
{
    /**
     * 商品列表
     *
     * @return \think\Response
     */
    public function goodsList():Json {
        try {
            //echo "begin check:<br/>";
            validate(GoodsListValidate::class)
                //->scene('edit')
                ->check($_GET);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            //echo "get error:<br/>";
            //var_dump($e->getError());
            return Result::Error(422,$e->getError());
        }
 
        $data = [
        ['id'=>"1",'name'=>"牙刷"],
        ['id'=>"2",'name'=>"杯子"],
        ];
        return Result::Success($data);
    }
 
 
    /**
     * 登录
     *
     * @return \think\Response
     */
    public function login():Json {
        try {
            //echo "begin check:<br/>";
            validate(LoginValidate::class)
                //->scene('edit')
                ->check($_POST);
        } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                //echo "get error:<br/>";
                //var_dump($e->getError());
                return Result::Error(422,$e->getError());
        }
 
        if ($_POST["username"] == "dddddd" && $_POST["password"] == "111111"){
            //echo "success:<br/>";
            return Result::Success("success");
        } else {
            //echo "error:<br/>";
            return Result::Error(422,"用户名密码错误");
        }
    }
}

三,测试效果:

1,访问:
http://127.0.0.1:8000/auth/goodslist?categoryId=a
返回:
2,访问:
http://127.0.0.1:8000/auth/goodslist?categoryId=0
返回:
3,访问:
http://127.0.0.1:8000/auth/goodslist?categoryId=5
返回:
4,访问:
http://127.0.0.1:8000/auth/goodslist?categoryId=5&channelId=a1@2
返回:
5,访问:
http://127.0.0.1:8000/auth/goodslist?categoryId=5&channelId=a1ddd
返回:

四,查看php和thinkphp的版本:

php:
root@lhdpc:~# php --version
PHP 8.0.14 (cli) (built: Dec 23 2021 11:52:42) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.14, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.14, Copyright (c), by Zend Technologies
thinkphp:
root@lhdpc:~# cd /data/php/admapi/
root@lhdpc:/data/php/admapi# php think version
v6.0.9 
原文地址:https://www.cnblogs.com/architectforest/p/15746857.html