1、打印出当前模型
api/modules/v1/models/PlanTask Object ( [_attributes:yii/db/BaseActiveRecord:private] => Array ( [id] => 3 [group_id] => 015ce30b116ce86058fa6ab4fea4ac63 [config_column_id] => 1 [plan_id] => 1 [sort_order] => 1 [title] => 无线成都1 [config_task_id] => 1 [create_user_id] => 8 [create_name] => 13281105967 [exec_user_id] => 185 [exec_name] => test1 [place] => 地点 [task_info] => <p>选题摘要</p> [task_data] => a:0:{} [ended_at] => 1530695128 [current_step_id] => 18 [prev_status] => 2 [status] => 1 [created_at] => 1528103128 [updated_at] => 1528188754 ) ] )
2、现在有请求参数,tool,必填,工具标识,jove:Jove微编;nova:Nova精编,且验证范围([jove, nova]);
3、由于tool不存在于模型 api/modules/v1/models/PlanTask 中,因此需要执行临时验证,代码如下
use yii/base/DynamicModel; class VideoEditAction extends Action { const TOOL_JOVE = 'jove'; //工具:Jove微编 const TOOL_NOVA = 'nova'; //工具:Nova精编 // 临时验证 $request = Yii::$app->request; $tool = $request->get('tool'); $dynamicModel = new DynamicModel(compact('tool')); $dynamicModel->addRule('tool', 'required') ->addRule('tool', 'in', ['range' => [self::TOOL_JOVE, self::TOOL_NOVA]]) ->validate(); if ($dynamicModel->hasErrors()) { $response = Yii::$app->getResponse(); $response->setStatusCode(422, 'Data Validation Failed.'); foreach ($dynamicModel->getFirstErrors() as $message) { $firstErrors = $message; break; } return ['code' => 20004, 'message' => Yii::t('error', Yii::t('error', Yii::t('error', '20004'), ['firstErrors' => $firstErrors]))]; } }
4、在 Postman 中测试,当不填写 tool 参数时,符合预期,如图1
{ "code": 20004, "message": "数据验证失败:Tool不能为空。" }
5、在 Postman 中测试,当 tool 参数不等于([jove, nova])时,符合预期,如图2
{ "code": 20004, "message": "数据验证失败:Tool是无效的。" }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/181136.html