Thinkphp6笔记十三:验证器(场景验证)


控制器调用:

public function test3(){
        $data = [
            'name'  => '',
            'age'   => 130,
            'email' => '111',
        ];

        $validate = new \app\admin\validate\User;
        // 验证全部字段
        //$result = $validate->check($data);
        // 选取某个场景验证
        $result = $validate->scene('email')->check($data);

        if(!$result){
            echo $validate->getError();
        }
    }

验证器代码:\app\admin\validate\User.php

<?php
namespace app\admin\validate;

use think\Validate;

class User extends Validate
{
    protected $rule =   [
        'name'  => 'require|max:25',
        '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'],
        'email'=>['email']
    ];

}

************************************************

Thinkphp高级交QQ流群:101766150

作者:狂奔的蜗牛

转载请注明出处

************************************************