yii2验证码的一些心得

1.在控制器中加入

public function actions() {
        return [
            'captcha' =>  [
                'class' => 'yii\captcha\CaptchaAction',
                'height' => 50,
                'width' => 80,
                'minLength' => 4,
                'maxLength' => 4
            ],
        ];
    }

2.如果数据库没有验证码的字段记得先声明一个验证码的模型

 public  $verifyCode;

在models模型的rules方法中加入

 public function rules()
    {
        return [

            ['verifyCode', 'captcha','captchaAction'=>'index/captcha','message'  =>'验证码错误']

        ];
    }

captchaAction 指定captcha所在的控制器路径,默认是‘site/captcha’,不换到指定位置的话,很容易,验证码就显示不出来。
3.然后在models模型中加入

 public function attributeLabels()
    {
        return[
            'verifyCode'=>"验证码",
        ];
    }

4接下来是视图view中加入

<?php 
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
?>
在添加验证码的时候加入
<?php 
echo $form->field($model,'verifyCode',[ 'template'  =>
                   '<div  class="row cl"><div class="formControls col-8 col-offset-3">{input}'.Captcha::widget([
                       'model' =>$model,
                       'attribute' =>'verifyCode',//模型中也要申明
                       'captchaAction' =>'index/captcha',//指定操作
                       'template'  =>'{image}',//image代表此处生成验证码图片
                       'imageOptions'   =>[
                           //以下atrribute属性,可自己扩展
                           'title'  =>'点击刷新''style' =>'margin-left:20px;'
                       ],
                   ]).'{error}</div></div>'])->textInput(['class'=>'input-text size-L','placeholder'=>'验证码','style'=>'width:150px,padding-left:25px']);?>

imageOptions设定一些参数,例如 手势,提示等等。
对应布局中,如下:以确保你在点击验证码可以自动刷新

<?php $this->beginPage() ?>
<?php $this->beginBody() ?>
//your codes...
<?= $contents; ?>
//your codes...
<?php $this->endBody() ?>
<?php $this->endPage() ?>

最后,控制器中调用render而非renderPartial

return $this->render('login',['model'=>$model]);

参考博客
刷新验证码不更新的解决方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值