Yii2.0同一个页面使用多个验证码

Yii2.0框架对实现的抽象层次很高,导致我们使用的时候完全跟着文档走,但是文档又写的很粗糙,我个人认为,写Yii2.0的人不喜欢写文档,希望我们自己去读源码。
如果需要在同一个页面,使用不同的验证码,怎么办?这个就要根据验证码的机制来找答案了。
先看看验证码的使用方法:

在需要使用验证码的比如User控制器中的actions方法中添加设置:
public function actions() {
return [
‘captcha’ => [
‘class’ => ‘yii\captcha\CaptchaAction’,
‘height’ => 50,
‘width’ => 80,
‘minLength’ => 4,
‘maxLength’ => 4
],
];
}

然后就可以在视图中加入验证码了。

<?php 
use yii\captcha\Captcha; 
echo $form->field($user_login,'captcha')->widget(yii\captcha\Captcha::className(),
[
'captchaAction'=>'user/captcha',
'imageOptions'=>[
'alt'=>'点击换图',
'title'=>'点击换图',
'style'=>'cursor:pointer',
]
]);
?>

在User控制器中验证验证码是否正确:

$this->createAction('captcha')->validate($captchCode, false); //$captchCode为用户输入的验证码

那么,我们如果要在同一个页面中使用2个验证码,怎么办呢?
其实只需要在actions里设置两个action就可以了:

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

试图中:

<?php 
use yii\captcha\Captcha; 
echo $form->field($user_login,'captcha')->widget(yii\captcha\Captcha::className(),
    [
    'captchaAction'=>'user/captcha1',
    'imageOptions'=>[
    'alt'=>'点击换图',
    'title'=>'点击换图',
    'style'=>'cursor:pointer',
    ]
]);
echo $form->field($user_login,'captcha')->widget(yii\captcha\Captcha::className(),
    [
    'captchaAction'=>'user/captcha2',
    'imageOptions'=>[
    'alt'=>'点击换图',
    'title'=>'点击换图',
    'style'=>'cursor:pointer',
    ]
]);
?>

验证同理可得:

$this->createAction('captcha1')->validate($captchCode1, false); //$captchCode1为用户在第一个验证码input中输入的验证码
$this->createAction('captcha2')->validate($captchCode2, false); //$captchCode2为用户在第二个验证码input中输入的验证码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值