Respect \ Validation \ Validator。我有一个验证器课程 validator.php
<?php
namespace app\http\validations;
use Respect\Validation\Validator as Respect;
use Respect\Validation\Exceptins\NestedValidationException;
class Validator {
protected $errors = [];
public function validate($request, array $rules){
foreach ($rules as $field => $rule) {
try{
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $ex) {
$this->errors[$field] = $ex->getMessages();
}
}
return $this;
}
public function failed(){
return !empty($this->errors);
}
}
然后我在控制器中使用此验证,这是我的控制器:
<?php
namespace app\http\controllers\v1;
use Slim\Http\Request;
use Slim\Http\Response;
use Respect\Validation\Validator as v;
use app\providers\v1\CompanyServiceProvider;
class CompanyController extends BaseApiController {
public $companyServiceProvider;
public function __construct() {
$this->companyServiceProvider = new CompanyServiceProvider();
}
public function saveBasicDetails(Request $request, Response $response) {
$validator = new \app\http\validations\Validator();
$validation = $validator->validate($request, [
'company_name' => v::notEmpty()->alpha()
]);
if($validation->failed()){
print_r($validation); die;
}
$result = $this->companyServiceProvider->saveBasicDetails($request);
return BaseApiController::returnResponse($response, $result);
}
}
这是我的路线,我正在从该路线调用saveBasicDetails函数。
$app->post('/save-basic-details', \app\http\controllers\v1\CompanyController::class. ':saveBasicDetails');
我遇到以下错误:这些规则必须通过Company_name
我想返回JSON中的验证错误。
答案 0 :(得分:1)
在控制器中,您必须将容器注入构造函数中,然后定义一个getter来获取验证器。检查一下link,到目前为止,没有什么像symfony autowire一样必须显式注入容器并获得所需的服务的。在下面检查此代码将对您有帮助!
//use Psr\Container\ContainerInterface;
/**
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
//Then define a getter
/**
* @return Validator
*/
protected function getValidator()
{
if (!$this->validator instanceof Validator) {
$this->validator = $this->container->get('Validator');
}
return $this->validator;
}
//Then access the validator
$this->getValidator()->validate...
答案 1 :(得分:0)
伙计们我犯了一个愚蠢的错误,其中有一个拼写错误
use Respect\Validation\Exceptins\NestedValidationException;
更改为
use Respect\Validation\Exceptions\NestedValidationException;
解决了我的问题。