yii2 验证码的使用

@see  http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.htmlphp

如下根据 MVC 模型的顺序来添加代码html

1. model 层, 或者能够在默认的 LoginForm.php 上修改, 代码以下. yii2

class LoginForm extends Model
{
    // ......表示其余人码.
    ......
    // 添加验证码属性字段
    public $verifyCode;
    ......

    public function rules()
    {
        return [
            ......
            ['verifyCode', 'captcha', 'captchaAction' => '/admin/login/captcha'],
            ......
        ];
    }
}

若是使用默认 SiteController 控制器, 红包部分代码可不用填写, 若是使用其余好比我使用 http://my-domain.net/admin/login 控制器, 那红色部分就得添加了, 否则的话, 会提示 app

Exception (Invalid Configuration) 'yii\base\InvalidConfigException' with message 'Invalid CAPTCHA action ID: default/captcha'in E:\wamp\www\yii-application\vendor\yiisoft\yii2\captcha\CaptchaValidator.php:81

@see http://stackoverflow.com/questions/28497432/yii2-invalid-captcha-action-id-in-moduledom

 

2. view 层, 属性设置参考  http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html, 代码以下yii

        <?= $form
            ->field($model, 'verifyCode')
            ->label(false)
            ->widget(Captcha::className(), [
                'template' => '<div class="row"><div class="col-lg-6">{input}</div><div class="col-lg-3">{image}</div></div>',
                'captchaAction' => 'login/captcha',
                'options' => ['placeholder' => 'VerifyCode', 'class' => 'form-control'],
                ])
        ?>

 

3. 控制器里添加以下代码,  或者能够直接去默认 SiteController 里复制一份是同样的. 属性设置参考 http://www.yiiframework.com/doc-2.0/yii-captcha-captchaaction.html spa

    /**
     * actions
     */
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'maxLength' => 5,
                'minLength' => 5,
            ],
        ];
    }
相关文章
相关标签/搜索