tinywan/validate

validate for webman plugin

v1.0.2 2024-05-20 07:11 UTC

This package is auto-updated.

Last update: 2024-10-20 08:12:43 UTC


README

Latest Stable Version Total Downloads webman-event webman-event webman-event webman-event

基于ThinkPHP6修改的可用于 webman 的通用validate数据验证器。

安装

composer require tinywan/validate

基础用法

<?php
namespace app\index\validate;

use Tinywan\Validate\Validate;

class UserValidate extends Validate
{
    protected array $rule =   [
        'name'  => 'require|max:25',
        'age'   => 'require|number|between:1,120',
        'email' => 'require|email'
    ];

    protected array $message  =   [
        'name.require' => '名称必须',
        'name.max'     => '名称最多不能超过25个字符',
        'age.require'   => '年龄必须是数字',
        'age.number'   => '年龄必须是数字',
        'age.between'  => '年龄只能在1-120之间',
        'email.require'        => '邮箱必须是数字',
        'email.email'        => '邮箱格式错误'
    ];
}

验证器调用代码如下:

$data = [
    'name'  => 'Tinywan',
    'age'  => 24,
    'email' => 'Tinywan@163.com'
];
$validate = new app\index\validate\UserValidate;

if (!$validate->check($data)) {
    var_dump($validate->getError());
}

助手函数(推荐)

$data = [
    'name'  => 'Tinywan',
    'age'  => 24,
    'email' => 'Tinywan@163.com'
];
validate($data, \app\index\validate\UserValidate::class);

验证错误会自动抛出异常

使用面板Facade

$validate = \Tinywan\Validate\Facade\Validate::rule('age', 'number|between:1,120')
    ->rule([
        'name'  => 'require|max:25',
        'email' => 'email'
    ]);
$data = [
    'name'  => 'tinywan',
    'email' => 'tinywan@gmail.com'
];
if (!$validate->check($data)) {
    var_dump($validate->getError());
}

更多用法可以参考6.0完全开发手册的验证章节