TP6场景验证问题

2023-12-14 11:54:35

场景验证类如下:

class Client extends Validate{

    protected $rule = [
        'name'      => 'require|checkName',
        'address'   => 'require',

    ];

    protected $message = [
        'name.require'      => '请输入商超名称',
        'address.require'   => '地址不能为空',

    ];

    //验证场景,经测试这个是不起作用的
//    protected $scene = [
//        'edit'  => ['name'],
//        'add'   => ['name,address']
//    ];

    public function sceneEdit(){
        return $this->only(['name','address']);
    }

    public function sceneAdd(){
        return $this->only(['name']);
    }

    protected function checkName($value,$rule,$data = []){
        $map = [
            ['dealer_id','=',$data['dealer_id']],
            ['name','=',$value],
        ];
        if(isset($data['id']) && $data['id'] > 0){
            $map[] = ['id','<>',$data['id']];
        }

        $cInfo = \app\sells\model\Client::where($map)->find();

        if(isset($cInfo['id'])) return '同客户下名称重复';
        return true;
    }
}

调用方法:

//编辑
$this->validate($data,'\app\sells\validate\Client.edit');

//添加
$this->validate($data,'\app\sells\validate\Client.add');

因为在baseController.php中定义了 validate函数,如下:

protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

文章来源:https://blog.csdn.net/hotlinhao/article/details/134916408
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。