Yii2 captcha validation in the form with an easy way

By | June 16, 2019

Hello Coders !! This article is for the integration of Yii2 captcha validation in the form in an easy way. Sometimes, unwanted users visit the site and filling up the form and try to spam our site and forms. So at that time captcha will be helpful to separate those users from the calibrated users.

Let’s get started with the following steps.

Hope you guys already installed any project with Yii2 Framework.

Here are Steps to follow

There are three steps to make these thing work. You just need to create the three file of Model, view, and controller and you are ready to use captcha validation in YII2 framework.

So let’s start with creating a view file.

Step 1: Create a view

Create a view file “views/example.php

You need to add this file in view folder and you will find this folder here.

<root>/<project>/frontend/views/
<?php

/*
 * Add namespace for captcha at the top of the view file
 */
use yii\captcha\Captcha;

?>

<!-- Add below code in ActiveForm where we want to display captcha in our website. Make sure this should be inside ActiveForm -->

<div class="form-group">
    <?= $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::classname(), [
    // configure additional widget properties here
]) ?>
</div>

Step 2: Create a Controller

Create a Controller file “ExampleController.php

You need to add this file in the controller folder and you will find this folder here.

<root>/<project>/frontend/controllers/
<?php
namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use app\controllers\BaseController;
use yii\web\Controller;
use app\models\Example;

/*
* Other namespace here
*/

/**
 * Example controller
 */
class ExampleController extends BaseController
{
    /* Write behaviour code */
    public function behaviors()
    {
       return [
            'access' => [
                'class' => AccessControl::className(),
                 // Set rules based on our need, like at which page we showing captcha and its public or need user login
                 'rules' => [
                     [
                        'actions' => ['captcha'],
                        'allow' => true,
                     ],
                     /*[
                        'actions' => ['captcha'],
                        'allow' => true,
                        'roles' => ['@'],
                     ],*/
                ],
             ]
       ]
    }
    
    //Save function where we store data in database table
    public function actionSave()
    {
        $model = new Example();
        if ($model->load(Yii::$app->request->post())) {
              if ($model->validate()) {
                 $model->save(false); // Make sure you do add 'false' else your captcha may change at this moment and we will get captcha unverified error again and again.
              }
        }
    }

    // Write below code in actions function including with our other code like handling error etc.
    public function actions()
    {
        return [            
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
            ],
        ];
    }
}
?>

Step 3: Create a Model

Create a Model file “Example.php

You need to add this file in the model folder and you will find this folder here.

<root>/<project>/frontend/models/
<?php

namespace app\models;

use Yii;

class Example extends Base
{
    public $captcha;
    
    public function rules()
    {
        return [
           /*
           *
           * Other rules will goes here :)
           */
           ['captcha','captcha', 'captchaAction' => 'ControllerName/captcha', 'caseSensitive' => false],
        ];
    }
}

?>

This is it you are done with the Yii2 captcha validation in a form with an easy way in YII Framework.
Let us know if you found any difficulties in this article we would love to help you out!

If you have anything to tell us please comment here

Happy Coding! Good Luck!

Leave a Reply

Your email address will not be published. Required fields are marked *