PHP code example of imeepo / validate

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

    

imeepo / validate example snippets


namespace app\validate;

use imeepo\validate\Validate;

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

namespace app\controller;

use app\validate\User;
use imeepo\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'  => 'imeepo',
        'age'   => 18,
        'email' => '[email protected]',
    ];

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

    // 静态方法验证
    $validate = \imeepo\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 imeepo
 */
function validate($validate = '', array $message = [], bool $batch = false, bool $failException = true)
{
    if (is_array($validate) || ''===$validate) {
        $v = new \imeepo\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);
}