thinkphp6-验证

验证器使用

命令行生成User验证器

php think make:validate User

验证器添加规则 app\validate\User.php

<?php
declare (strict_types = 1);

namespace app\validate;

use think\Validate;

class User extends Validate
{
    /**
     * 定义验证规则
     * 格式:'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'name'  =>  'require|max:8'
    ];

    /**
     * 定义错误信息
     * 格式:'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'name.require' => '名称必须',
        'name.max'     => '名称最多不能超过8个字符',
    ];

}

数据验证 控制器 app/controller/Index.php

<?php

namespace app\controller;

use app\validate\User;
use think\exception\ValidateException;
class Index
{
    public function index()
    {
        try {
            validate(User::class)->check([
                'name'  => '胡勇健',
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            dump($e->getError());
        }

    }
}

测试(修改name变量名,长度)

http://127.0.0.1:8000/index

验证器规则

protected $rule = [
      'name'  => 'require|max:25',
      'age'   => 'number|between:1,120',
      'email' => 'email',
    ];
protected $rule = [
      'name'  => ['require', 'max' => 25, 'regex' => '/^[\w|\d]\w+/'],
      'age'   => ['number', 'between' => '1,120'],
      'email' => 'email',
    ];

错误信息

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

验证场景

protected $scene = [
        'edit'  =>  ['name','age'],
    ]; 
$data = [
    'name'  => 'thinkphp',
    'age'   => 10,
    'email' => 'thinkphp@qq.com',
];

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

内置规则

'name'=>'require'
'num'=>'number'
'num'=>'integer'
'num'=>'float'
'num'=>'boolean'
'email'=>'email'
'info'=>'array'
'date'=>'date'
'name'=>'chsDash'
'name'=>'lower'
'url'=>'url'
'ip'=>'ip'
'mobile'=>'mobile'
'mac'=>'macAddr'
'num'=>'in:1,2,3'
'num'=>'notIn:1,2,3'
'num'=>'between:1,10'
'name'=>'max:25'
posted @ 2021-10-18 16:14  胡勇健  阅读(316)  评论(0)    收藏  举报