igou igou - 1 month ago 18
Ajax Question

Why Yii2 captcha can't through the verification On the client side?

I am using Yii2 admin Module, the captcha image is shown on the form. After I input the verifycode, tips always shown the error message on the client side, but I'm sure it was entered correctly. Then I view the source code, I found I didn't set the attribute

captchaAction
(
\yii\captcha\CaptchaValidator
) correctly, the default value of
captchaAction
is
site/captcha
, but my controller is
app\modules\admin\controllers\PublicController
, I think that the value of captchaAction should be
admin/public/captcha
, but how to set it ?

The following is my view page code:

<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-4">{image}</div> &nbsp;<div class="col-lg-7">{input}</div></div>',
'captchaAction' => 'public/captcha',
]); ?>


Here is my controller:

public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'minLength' => 3,
'maxLength' => 5,
],
];
}
public function actionLogin()
{
$model = new LoginForm();
if ( Yii::$app->request->isPost ) {
# code ...
} else {
return $this->render('login', [
'model' => $model,
'title' => Yii::$app->params['adminLogin'],
]);
}
}

Answer

Careful with form which is validated by AJAX. Captcha of Yii will be reload if you validate by Ajax. So with this case, we can solve with two option:

  1. Disable ajaxValidation, enable clientValidation. Such as: signup form
$form = ActiveForm::begin([
    'id'                     => 'registration-form',
    'enableAjaxValidation'   => true,
    'enableClientValidation' => false
]);
  1. Override function validate of CaptchaAction, don't getVerifyCode through AJAX.
if(\Yii::$app->request->isAjax == false) {
    $this->getVerifyCode(true);
}
Comments