yii2 驗證碼的使用


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

以下根據 MVC 模型的順序來添加代碼

1. model 層, 或者可以在默認的 LoginForm.php 上修改, 代碼如下. 

class LoginForm extends Model
{
    // ......表示其他人碼.
    ......
    // 添加驗證碼屬性字段
    public $verifyCode;
    ......

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

如果使用默認 SiteController 控制器, 紅包部分代碼可不用填寫, 如果使用其他比如我使用 http://my-domain.net/admin/login 控制器, 那紅色部分就得添加了, 不然的話, 會提示 

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-module

 

2. view 層, 屬性設置參考  http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html, 代碼如下

        <?= $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 

    /**
     * actions
     */
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'maxLength' => 5,
                'minLength' => 5,
            ],
        ];
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM