@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, ], ]; }