1. 在控制器中定义生成验证码方法
public function actions(){ //必须以actions() 为方法名
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength' => 4,
'minLength' => 4,
'width'=>120,
'height'=>50,
'padding' => 2, //间距
'foreColor'=>0x2040A0, //字体颜色
'offset'=>-2, //设置字符偏移量 有效果
],
];
}
2.在模型定义验证规则
['verifyCode', 'captcha', 'captchaAction'=>'admin/login/captcha','message'=>'验证码错误', 'on' => 'login'],
3. 在视图中使用
①、先引入Captcha类:
use yii\captcha\Captcha;
②、然后再输出
在 'captchaAction'=>'login/captcha'
参数中 ,值为:'自定义控制器名/captcha'
,'/'后面的 captcha 固定不变
<?=$form->field($model, 'verifyCode')->widget(Captcha::className(), [
'captchaAction' => 'login/captcha',
'imageOptions'=>['alt'=>'点击换图','title'=>'点击换图', 'style'=>'cursor:pointer'],
'options' => ['placeholder' => '验证码', 'class' => 'verify'],
'template' => '<div class="row"><div class="col-lg-6">{input}</div><div class="col-lg-3">{image}</div></div>',])?>
//点击刷新验证码
<script type="text/javascript">
var obj = document.getElementById('admin-verifycode-image');
obj.onclick=function(){
obj.src = obj.src + "&t="+Date.parse(new Date());
};
</script>
4. 解决验证码不刷新
网上的大多数解决方法都是通过修改vendor/yiisoft/yii2/captcha/CaptchaAction.php
中的代码来解决
①修改run()方法
Tip:使用上面两种方法确实都可以解决验证码不刷新的问题,但这样会带来一个新的问题,就是在开启表单客户端验证(enableClientValidation)的情况下,即使用户输入了正确的验证码,网页仍然会提示“验证码错误”:
本文链接:https://www.23thi.com/336.html
除非特殊声明,本站文章均为原创,转载请务必保留本文链接