Nur Diarto
Nur Diarto

Reputation: 55

yii2 captcha validation not work

I'm trying to add captcha to my login page on my yii2 application. I have tried some tutorial, the problem is captcha is always correct like no validation.

I have tried this:

My code is:

LoginForm

public $username;
public $password;
public $rememberMe = true;
private $_user = false;
public $captcha; // add this varible to your model class.

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            // username and password are both required
            [['username', 'password','captcha'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            ['captcha', 'captcha','captchaAction'=>'/site/captcha'], // add this code to your rules.
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

SiteController

 public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,

            ],
        ];
    }

view login.php

 <div class="form-goup">
           <?= $form->field($model, 'captcha')->widget(yii\captcha\Captcha::className(), '
['template' => '<div class="row"><div class="col-lg-3" style="margin-right:25px;">{image}</div><div class="col-lg-6">{input}</div></div>',
            ]); ?> 
    </div>

Upvotes: 0

Views: 2039

Answers (2)

luk
luk

Reputation: 355

I know the topic is old but it might be the issue with your url rules. Have you tried adding:

'captcha'=>site/captcha' 

in your config file, url section

Upvotes: 0

Vladimir
Vladimir

Reputation: 445

Your code works but you have syntax errors in it, a letter (this is only cosmetic) and a surplus ' which is completely wrong:

<div class="form-group">
    <?= $form->field($model, 'captcha')->widget(yii\captcha\Captcha::className(), ['template' => '<div class="row"><div class="col-lg-3" style="margin-right:25px;">{image}</div><div class="col-lg-6">{input}</div></div>',]); ?> 
</div>

This should be in view before submit button <?php ActiveForm::end(); ?>

Upvotes: 1

Related Questions