yii2中的验证码

tp中给的验证码非常好用,那么yii2中怎么会少


第一步,在controller中actions方法中添加captcha数组,如果没有actions方法,那就重写一个。

public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],

//            'captcha'=>array(
//                'class'=>'CCaptchaAction',
//                'backColor'=>0xFFFFFF,
//            ),
//            'captcha' => [
//                'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//                'maxLength' => 5,
//                'minLength' => 5
//            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//                'backColor'=>0x000000,//背景颜色
//                'maxLength' => 5, //最大显示个数
//                'minLength' => 5,//最少显示个数
//                'padding' => 5,//间距
//                'height'=>30,//高度
//                'width' => 130,  //宽度
//                'foreColor'=>0xffffff,     //字体颜色
//                'offset'=>4,        //设置字符偏移量 有效果
                // 'controller'=>'site',        //拥有这个动作的controller
            ],
        ];
    }
这里多讲一句actions方法,actions方法里面配置的数组key都可以当做action来用,比如IndexController中的actionIndex的访问方法为index/index,在indexcontroller中添加上面写的actions方法,那index/captcha就可以访问到一张二维码图片。


第二步,在model中添加代码,提供验证码的验证。

public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password', 'verifyCode'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
            // verifyCode needs to be entered correctly
           <strong> ['verifyCode', 'captcha', 'message'=>'验证码输入不正确'],// 验证码的验证规则</strong>
        ];
    }


第三部,在view中使用


<?= $form->field($model, 'verifyCode')->textInput() ?>

    <?= Captcha::widget([
        'name' => 'verify',
        'imageOptions' => [
            'id' => 'verify',
            'title' => '换一个',
            'alt' => '换一个'
        ],
        'template' => '{image}'
    ]); ?>


ok,验证码这样就可以正常使用了

猜你喜欢

转载自blog.csdn.net/zlh13854157321/article/details/52035351
今日推荐