侧边栏壁纸
博主头像
云BLOG 博主等级

行动起来,活在当下

  • 累计撰写 318 篇文章
  • 累计创建 6 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
WEB

ThinkPHP 8通用验证模块实现

Administrator
2025-03-13 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

php

<?php
namespace app\validate;

use think\Validate;

class BaseValidate extends Validate
{
    // 场景配置
    protected $scene = [];
    
    // 当前场景
    protected $currentScene = null;

    /**
     * 设置验证场景
     * @param string $scene 场景名称
     * @return $this
     */
    public function scene($scene)
    {
        $this->currentScene = $scene;
        return $this;
    }

    /**
     * 动态添加规则
     * @param string $field 字段名
     * @param string $rule 规则
     * @param string $msg  错误提示
     */
    public function addRule($field, $rule, $msg = '')
    {
        $this->rule[$field] = $rule;
        if ($msg) {
            $ruleName = current(explode('|', $rule));
            $this->message[$field.'.'.$ruleName] = $msg;
        }
    }

    /**
     * 添加自定义验证方法
     * @param string $name 方法名
     * @param callable $callback 回调函数
     */
    public function addMethod($name, callable $callback)
    {
        $this->extend($name, $callback);
    }

    /**
     * 验证入口
     * @param array $data 数据
     * @param string $scene 场景
     * @param bool $batch 是否批量验证
     * @return bool
     */
    public function check($data, $scene = '', $batch = false)
    {
        // 场景处理
        if ($scene) {
            $this->currentScene = $scene;
        }

        // 应用场景限制
        if ($this->currentScene && isset($this->scene[$this->currentScene])) {
            $this->only = $this->scene[$this->currentScene];
        }

        return parent::check($data, $this->currentScene, $batch);
    }
}

使用示例:

php

// 1. 创建具体验证器
class UserValidate extends BaseValidate
{
    // 内置规则
    protected $rule = [
        'username' => 'require|max:25',
        'age'      => 'number|between:1,120',
    ];

    // 错误提示
    protected $message = [
        'username.require' => '用户名必须',
        'age.between'     => '年龄必须在1-120之间'
    ];

    // 场景定义
    protected $scene = [
        'register' => ['username', 'age'],
        'login'    => ['username']
    ];

    // 自定义验证方法
    protected function checkMobile($value)
    {
        return preg_match('/^1[3-9]\d{9}$/', $value);
    }
}

// 2. 使用示例
$data = [
    'username' => 'thinkphp',
    'age'      => 25,
    'mobile'   => '13800138000'
];

$validate = new UserValidate();

// 动态添加规则
$validate->addRule('mobile', 'require|checkMobile', '手机号格式错误');

// 添加自定义方法(可选方式)
$validate->addMethod('checkMobile', function($value) {
    return preg_match('/^1[3-9]\d{9}$/', $value);
});

// 场景验证
if (!$validate->scene('register')->check($data)) {
    // 批量获取错误
    dump($validate->getError());
}

// 批量验证示例(遇到错误继续验证)
$validate->check($data, 'register', true);

主要特性说明:

  1. 场景验证:通过scene方法指定场景,自动应用对应字段规则

  2. 动态规则:支持运行时通过addRule添加验证规则

  3. 自定义方法

    • 可以直接在验证器类中定义 check+方法名 的验证方法

    • 或通过addMethod动态添加验证方法

  4. 批量验证:check方法的第三个参数控制是否批量验证

  5. 继承扩展:继承自官方Validate类,保持框架原生功能

注意事项:

  1. 场景定义使用protected $scene属性

  2. 自定义方法需要以check开头(框架原生特性)

  3. 动态添加的规则会覆盖原有规则

  4. 批量验证模式下会返回所有错误信息

可以根据实际需求继续扩展更多验证规则,同时保持代码的简洁性。这种实现方式既保留了ThinkPHP原生验证器的特性,又增强了动态扩展能力。

0

评论区