Yii2.0自定义验证码
控制器
假设控制器为Auth,则在该控制器下重载actions,以下是基本的配置,更多的配置请查看官方文档 yii-captcha-captchaaction 章节
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'testLimit' => 2,//两次有效
'height' => 40,
'width' => 80,
'minLength' => 4,
'maxLength' => 4
]
];
}
模型
假设验证码的字段为verifyCode,则在模型下的验证规则rules方法下,添加,注意captchaAction要配置正确,要和前端的配置对应.
public $verifyCode;
public function rules()
{
return [
['verifyCode','captcha','captchaAction'=>'admin/auth/captcha','message'=>'验证码不正确'],
];
}
视图
有两种调用方式,个人比较喜欢第二种.
方式一
<?php $form=\yii\bootstrap\ActiveForm::begin();?>
<?= $form->field($model,'verifyCode')->widget(\yii\captchat\Captcha::className,[
'captchaAction' =>'auth/captcha',//必须要和model中的一致
'template' => '{input}{image}', //模板
'options' => ['placeholder'=>'验证码'],//input框属性
'imageOptions' => ['id'=>'captcha'] //图像的属性
]);?>
<?php $form->end();?>
方式二
<?php $form=\yii\bootstrap\ActiveForm::begin();?>
<?= \yii\captcha\Captcha::widget([
'model' => $model,
'attribute' => 'verifyCode',
'captchaAction' => 'auth/captcha',
'options' => ['placeholder'=>'验证码'],
'imageOptions' => ['id'=>'captcha'],
'template' => '{input}{image}',
]);?>
<?php $form->end();?>
以上是基本的配置,更多的配置请查看 官方文档 yii-captcha-captcha 章节
刷新
$("#captcha").click(function(){
var url = "<?= \yii\helpers\Url::to(['auth/captcha']);?>";
$.get(url,{refresh:1},function(data){
var object = eval(data);
$('#captcha').attr('src',object.url);
})
});
原文链接:https://blog.csdn.net/qq_34853874/article/details/70942895

浙公网安备 33010602011771号