daodao97 / apidog

Api Watch Dog, Hyperf 框架的 Api参数校验 和 swagger 生成组件
MIT License
150 stars 29 forks source link

怎么自定义验证规则? #59

Closed ZhengSheng1992 closed 3 years ago

ZhengSheng1992 commented 3 years ago

根据hyper文档写得自定义验证规则添加,识别不了 BadMethodCallException:Method Hyperf\Validation\Validator::validateFoo does not exist.(236) in /www/wwwroot/hyperf/vendor/hyperf/validation/src/Validator.php

ZhengSheng1992 commented 3 years ago
    $validator = $this->validationFactory->make(
        $param,
        [
            'amount' => 'required|foo',
        ],
        [
            'amount.required' => '请输入数量',
            'amount.foo' => '格式不正确',
        ]
    );

    if ($validator->fails()){
        // Handle exception
        $errorMessage = $validator->errors()->first();

        var_dump($errorMessage);
    }

这样验证是可以的 注解就不行

ZhengSheng1992 commented 3 years ago

Validation.php public function construct() { $this->container = ApplicationContext::getContainer(); $this->factory = $this->container->get(ValidatorFactory::class); $this->customValidateRules = $this->container->get(ValidationCustomRule::class); } 改成 public function construct() { $this->container = ApplicationContext::getContainer(); $this->factory = $this->container->get(ValidatorFactoryInterface::class); $this->customValidateRules = $this->container->get(ValidationCustomRule::class); } 即可

daodao97 commented 3 years ago

apidog 封装了内部校验逻辑, 不支持 hyperf 原生的自定义校验, image 如上图是控制器回调校验 的方式, 当然也支持更丰富的校验方式, 可以基于 ValidationCustomRule 扩展自己的校验规则.

原则上, 简单的, 一次性的校验使用控制器回调 的方式, 通用的, 可复用的 使用 扩展 ValidationCustomRule 的方式