PHP code example of hyperf-plus / validate

1. Go to this page and download the library: Download hyperf-plus/validate library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hyperf-plus / validate example snippets



use HPlus\Route\Annotation\PostApi;
use HPlus\Route\Annotation\ApiController;
use HPlus\Validate\Annotations\RequestValidation;

#[ApiController(prefix: '/api/users')]
class UserController
{
    #[PostApi]
    #[RequestValidation(
        rules: [
            'name' => 'c function create()
    {
        return ['message' => 'success'];
    }
}

// 定义验证器
use Hyperf\Validation\Request\FormRequest;

class CreateUserRequest extends FormRequest
{
    protected array $scenes = [
        'create' => ['name', 'email', 'password'],
        'update' => ['name', 'email'],
    ];

    public function rules(): array
    {
        return [
            'name' => 'rRequest::class, scene: 'create')]
public function create() {}

#[RequestValidation(
    rules: [],              // 请求体验证规则
    queryRules: [],         // URL 查询参数验证规则
    messages: [],           // 自定义错误消息
    attributes: [],         // 字段别名
    mode: 'json',           // 请求体解析模式:json | form | xml
    filter: false,          // 是否过滤多余字段
    security: false,        // 安全模式(拒绝未定义字段)
    stopOnFirstFailure: false,  // 首错即停
    validate: '',           // FormRequest 类名
    scene: '',              // 验证场景
)]

#[GetApi]
#[RequestValidation(
    queryRules: [
        'page' => 'integer|min:1',
        'size' => 'integer|between:1,100',
        'keyword' => 'nullable|string|max:50',
    ]
)]
public function list() {}

#[PostApi(path: '/search')]
#[RequestValidation(
    queryRules: [
        'page' => 'sc',
    ]
)]
public function search() {}

#[RequestValidation(
    rules: ['name' => 'ame/email 以外的字段,将抛出异常
)]

#[RequestValidation(
    rules: ['name' => 'name 和 email
)]

// config/autoload/dependencies.php
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\ValidatorFactory;

return [
    ValidatorFactoryInterface::class => function ($container) {
        $factory = $container->get(ValidatorFactory::class);
        
        $factory->extend('phone', function ($attribute, $value) {
            return preg_match('/^1[3-9]\d{9}$/', $value);
        });
        
        return $factory;
    },
];

// 使用
#[RequestValidation(rules: ['mobile' => '

#[RequestValidation(
    rules: [
        'users' => ''users.*.email' => '

#[RequestValidation(
    rules: [
        'type' => '8',
        'license' => '

// app/Exception/Handler/ValidationExceptionHandler.php
use HPlus\Validate\Exception\ValidateException;
use Hyperf\ExceptionHandler\ExceptionHandler;

class ValidationExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof ValidateException) {
            return $response->withStatus(422)->json([
                'code' => 422,
                'message' => $throwable->getMessage(),
            ]);
        }
        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidateException;
    }
}

// 3.x (旧)
#[Validation(validate: UserValidator::class, scene: 'create')]
#[RequestValidation(rules: [...], dateType: 'json')]

// 4.0 (新)
#[RequestValidation(validate: UserValidator::class, scene: 'create')]
#[RequestValidation(rules: [...], mode: 'json')]
bash
composer rf.php vendor:publish hyperf/translation

tests/
├── Unit/
│   ├── RuleParserTest.php          # 规则解析器测试
│   └── ValidationAspectTest.php    # 验证切面测试
├── Feature/
│   ├── ValidationRulesTest.php     # 验证规则功能测试
│   ├── ValidationModeTest.php      # 验证模式测试
│   └── ValidationAspectFullCoverageTest.php  # 完整覆盖测试
└── Performance/
    └── ValidationPerformanceTest.php  # 性能测试