PHP code example of yzh52521 / webman-validate

1. Go to this page and download the library: Download yzh52521/webman-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/ */

    

yzh52521 / webman-validate example snippets


namespace app\validate;

use yzh52521\validate\Validate;

class User extends Validate
{
    protected $rule =   [
        'name'  => 'name.> '年龄必须是数字',
        'age.between'  => '年龄只能在1-120之间',
        'email.

namespace app\controller;

use app\validate\User;
use yzh52521\validate\exception\ValidateException;

class Index
{
    public function index()
    {
        try {
            validate(User::class)->check([
                'name'  => 'thinkphp',
                'email' => '[email protected]',
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            dump($e->getError());
        }
    }
}

    //场景校验方法
    $data = [
        'name'  => 'thinkphp',
        'age'   => 10,
        'email' => '[email protected]',
    ];

    try {
        validate(app\validate\User::class)
            ->scene('edit')
            ->check($data);
    } catch (ValidateException $e) {
        // 验证失败 输出错误信息
        dump($e->getError());
    }

    // 静态方法验证
    $validate = \yzh52521\validate\facade\Validate::rule('age', 'number|between:1,120')
    ->rule([
        'name'  => '

$data = [
    'name'  => 'thinkphp',
    'age'  => 24,
    'email' => '[email protected]'
];
$validate = new \app\validate\User;

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

/**
 * @desc 验证器助手函数
 * @param string|array $validate 验证器类名或者验证规则数组
 * @param array $message 错误提示信息
 * @param bool $batch 是否批量验证
 * @param bool $failException 是否抛出异常
 * @return bool
 * @author yzh52521
 */
function validate($validate = '', array $message = [], bool $batch = false, bool $failException = true)
{
    if (is_array($validate) || ''===$validate) {
        $v = new \yzh52521\validate\Validate();
        $v->rule($validate);
    } else {
        if (strpos($validate, '.')) {
            [$validate, $scene] = explode('.', $validate);
        }
        $v = new $validate();
        if (!empty($scene)) {
            $v->scene($scene);
        }
    }
     return $v->message($message)->batch($batch)->failException($failException);
}