1.模型
模型中添加public $verifyCode;
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
class Adminuser extends ActiveRecord{
public $username;
public $password;
public $verifyCode;
public function rules(){
return [
['username','required','message'=>'用户名不能为空'],
['password','required','message'=>'密码不能为空'],
['verifyCode', 'captcha','message'=>'验证码输入错误'],
];
}
}
?>
2.控制器
添加方法
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
//验证码
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'backColor'=>0xffffff,//背景颜色
'maxLength' => 6, //最大显示个数
'minLength' => 5,//最少显示个数
'padding' => 5,//间距
'height'=>34,//高度
'width' => 120, //宽度
'foreColor'=>0x000000, //字体颜色
'offset'=>4, //设置字符偏移量 有效果
],
];
}
注意:可能你的验证码没有办法正常显示,这里可以删除控制器中的方法behaviors
3.视图
<?= $form->field($model, 'verifyCode')->widget('yii\captcha\Captcha', [
'captchaAction'=>'site/captcha',
'options' => [
'placeholder' => '输入验证码',
],
'template' => '<div class="row"><div class="col-lg-6">{input}</div><div style="margin-left:40px;margin-top:10px;" class="col-lg-3">{image}</div></div>',
])?>
4.我们这里回遇到一个问题,当我们刷新网页的时候我们会发现,我们的验证码并不会刷新,解决方法
找到文件/vendor/yiisoft/yii2/captcha/CaptchaValidator.php
修改
$code = $captcha->getVerifyCode(false);
为:
$code = $captcha->getVerifyCode(true);