欢迎加入laravel技术交流群 :784030154
网上yii2.0的验证码的资料很多,但是都比较散,今天对走的坑都清查一遍,下面的是我写的代码,可以直接用
1.控制器中,添加方法
public function actions(){
return [
'captcha'=>[
'class'=>'yii\captcha\CaptchaAction',
//'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'backColor'=>0x000000,
'maxLength'=>4,
'minLength'=>4,
'testLimit'=>1,//验证几次后刷新
]
];
}
2.模型中,添加验证规则
public function rules(){
return [
['verifycode', 'captcha', 'message'=>'验证码错误','captchaAction'=>'/admin/public/captcha'],//一定要指定captchaAction与控制器对应起来,否则一直会提示验证码错误
];
}
3.视图中,输入控件,并写一段ajax的验证码的地址替换js代码
echo $form->field($model,'verifycode')->widget(Captcha::className(),[
'captchaAction'=>'public/captcha',//指定生成验证码的路由
'template' => '{input}{image}',
'imageOptions'=>['alt'=>'点击换图','title'=>'点击换图', 'style'=>'cursor:pointer'],
])
$("#admin-verifycode-image").click(function(){
$.get("<?php echo yii\helpers\Url::to(['public/captcha','refresh'=>''])?>",function(res){
var data = JSON.parse(res);
$("#admin-verifycode-image").attr('src', data.url);
})
})
常见问题:
1.显示不了验证码
问题:1没有在视图中配置captchaAction,2.在控制器actions没有配置captcha对应的参数
2.点击验证码不刷新
解决:要在视图中,要写个ajax替换验证码图片的地址,
3.验证码一直都提示 验证码输入错误
解决:在模型中,captcha的验证规则中一定要指定captchaAction的路由地址,才会验证成功