TP6场景验证问题

场景验证类如下:

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);
    }

你可能感兴趣的:(php,thinkphp,表单验证)