没有不值得去解决的问题,也没有不值得去学习的技术!

Implementing Ad Hoc Validation in Yii 2.0 With Core Validators for Values Lacking a Model Class

Testing in Postman, when the tool parameter does not equal ([jove, nova]), it behaves as expected

1. Print the current model

Plaintext
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 is a request parameter, tool, which is required. It is a tool identifier: jove: Jove micro-editing; nova: Nova fine-editing, and the validation range is ([jove, nova]).

3. Since tool does not exist in the model api\modules\v1\models\PlanTask, ad-hoc validation is required. The code is as follows:

PHP

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. Testing in Postman, when the tool parameter is not provided, it behaves as expected, as shown in Figure 1.

Testing in Postman, when the tool parameter is not provided, it behaves as expected
Figure 1
JSON

{
    "code": 20004,
    "message": "数据验证失败:Tool不能为空。"
}

5. Testing in Postman, when the tool parameter does not equal ([jove, nova]), it behaves as expected, as shown in Figure 2.

Testing in Postman, when the tool parameter does not equal ([jove, nova]), it behaves as expected
Figure 2
JSON

{
    "code": 20004,
    "message": "数据验证失败:Tool是无效的。"
}

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系