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\Validate\Annotations\RequestValidation;
use HPlus\Route\Annotation\PostApi;
class UserController
{
#[PostApi]
#[RequestValidation(
rules: [
'username' => ' 验证通过后执行
$data = $this->request->getParsedBody();
// ...
}
}
#[RequestValidation(
rules: [
'username|用户名' => '龄' => 'integer|min:18|max:100',
'password|密码' => '
#[RequestValidation(
rules: [
'username' => ' [
'username.equired' => '请输入邮箱地址',
'email.email' => '邮箱格式不正确'
]
)]
#[RequestValidation(
rules: [
'user' => 'ser.email' => 'tring|max:200',
'tags' => 'array',
'tags.*' => 'string|distinct'
]
)]
#[RequestValidation(
rules: [
'type' => 'y_name' => ')]
use HPlus\Validate\ValidateRule;
// 注册自定义规则
ValidateRule::extend('phone', function ($attribute, $value, $parameters) {
return preg_match('/^1[3-9]\d{9}$/', $value);
});
// 使用自定义规则
#[RequestValidation(
rules: [
'mobile' => '
#[RequestValidation(
rules: [
'username' => '=> 'on create() {}
#[RequestValidation(
rules: [
'username' => 'string|min:3',
'email' => 'email',
'password' => 'string|min:6'
],
scene: 'update' // 更新场景(字段可选)
)]
public function update() {}
#[RequestValidation(
rules: [
'name' => 'on'
],
dateType: 'json' // 请求体类型:json(默认)、form、query
)]
#[RequestValidation(
rules: [
'email' => 'fore: function (&$data) {
// 前置处理:转换小写
$data['email'] = strtolower($data['email'] ?? '');
$data['username'] = trim($data['username'] ?? '');
}
)]
namespace App\Validator;
use HPlus\Validate\Validate;
class UserValidator extends Validate
{
protected array $rule = [
'username' => 'ray $message = [
'username.ssword'],
'update' => ['username', 'email'],
'login' => ['email', 'password']
];
}
// 使用验证器
#[PostApi]
#[RequestValidation(validator: UserValidator::class, scene: 'create')]
public function create() {}
#[GetApi]
#[RequestValidation(rules: [
'page' => 'integer|min:1|default:1',
'size' => 'integer|min:1|max:100|default:20',
'keyword' => 'string|max:50'
])]
public function index() {}
return [
// 默认错误码
'error_code' => 422,
// 默认错误消息
'error_message' => '验证失败',
// 是否返回所有错误
'return_all_errors' => true,
// 自定义错误格式
'error_format' => function ($errors) {
return [
'code' => 422,
'message' => '验证失败',
'errors' => $errors
];
}
];
// ✅ 正确:可选字段的空值被跳过验证
$rules = ['field' => 'min:3'];
$result = $validator->check(['field' => ''], $rules); // 返回 true
// ✅ 正确:必填字段的空值验证失败
$rules = ['field' => '
PHPUnit 10.5.47 by Sebastian Bergmann and contributors.
............................... 31 / 31 (100%)
Time: 00:00.041, Memory: 10.00 MB
OK (31 tests, 104 assertions)