Implementation of temporary validation of some values that are not bound to any model class on Yii 2.0 (using a core validator)
1. Print out the current model
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] =>
选题摘要
[task_data] => a:0:{}
[ended_at] => 1530695128
[current_step_id] => 18
[prev_status] => 2
[status] => 1
[created_at] => 1528103128
[updated_at] => 1528188754
)
]
)
2. Now there are request parameters, TOOL, required, tool ID, jove: jove micro-editing; nova: nova fine editing, and the verification range ([jove, nova]);
3. Since the tool does not exist in the model API\modules\v1\models\plantask, the temporary verification needs to be performed. The code is as follows
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. Test in Postman, when the TOOL parameter is not filled in, it meets the expectations, as shown in Figure 1
{
"code": 20004,
"message": "数据验证失败:Tool不能为空。"
}
5. Test in Postman, when the tool parameter is not equal to ([jove, nova]), as expected, as shown in Figure 2
{
"code": 20004,
"message": "数据验证失败:Tool是无效的。"
}

![在 Postman 中测试,当 tool 参数不等于([jove, nova])时,符合预期](https://www.shuijingwanwq.com/wp-content/uploads/2018/06/2-2.png)