[Yii2] Captcha in controller

Without using a model, we can generate and validate captcha on the fly:

Modify the vie1w file:
views/item/view.php:
> Note: i’m using kartik’s ActiveForm, but you can use Yii’s.

;['/item/data-ajax'], 'id'=>;'my-form' ]); echo \yii\captcha\Captcha::widget([ 'name' =>; 'captcha', 'captchaAction' =>; 'item/captcha', ]); echo 'Send'; \kartik\form\ActiveForm::end(); ?>

Then, in the Controller:
controllers/ItemController.php

[ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YIIENVTEST ? 'testme' : null, ], ]; } ... ... public function actionDataAjax(){ //... validations and stuff... // //get user's captcha input $captcha = Yii::$app->request->post("captcha"); //this creates Yii's CaptchaAction, $cv=$this->createAction('captcha'); //This validates the code, true if match. // each validation increments $testLimit, which is 3 by default. // you can see more at http://www.yiiframework.com/doc-2.0/yii-captcha-captchaaction.html if(!$cv->validate($captcha,true)){ //Deny return "Error: You shall not pass"; } else{ return "Success:Hey dude, what up?"; } ...

‘n that’s it.