[moka同学笔记]Yii2.0验证码

1.Model中Code.php

<?php
/**
 * Created by PhpStorm.
 * User: moka同学
 * Date: 2016/07/25
 * Time: 10:48
 */
namespace app\models;

use yii\base\Model;

class Code extends Model{
    public $verifyCode;

    public function rules()
    {
        return [
            ['verifyCode','captcha','captchaAction'=>'code/captcha','message'=>'验证码错误!']
        ];
    }
}
?>

2.控制器中CodeController.php

<?php
/**
 * Created by PhpStorm.
 * User: moka同学
 * Date: 2016/07/25
 * Time: 10:46
 */
namespace app\controllers;

use app\models\Code;
use yii\web\Controller;

class CodeController extends Controller{
    public function actions()
    {
        return [
            //验证码
            'captcha'=>[
                //验证码类
                'class'=>'yii\captcha\CaptchaAction',
                'maxLength'=>6, //生成验证码的长度最大为4
                'minLength'=>4, //生成最小个数4
                'width' =>80,   //宽度
                'height'=>40
            ]
        ];
    }

    public function actionIndex(){
        $code = new Code();
        if(\Yii::$app->request->isPost){
            //验证码验证
            if($code->validate()){
                echo "验证通过";
            }else{
                var_dump($code->getErrors());
            }
        }

        return $this->render('index',['model'=>$code]);

    }
}
?>

3.视图index.php

<?php
use \yii\helpers\Html;
use \yii\captcha\Captcha;
echo $this->render('@app/views/public/testNav');
?>
<?=Html::beginForm("",'post',['class'=>'forms'])?>
<?=Captcha::widget([
    'model'=>$model, //Model
    'attribute'=>'verifyCode',//字段
    'captchaAction'=>'code/captcha',//验证码的action 与 Model 是对应的,code/captcha
    'template'=>'{input}{image}', //模版,可以自定义
    'options'=>[
        //input 的Html属性配置
        'class'=>'input verifycode',
        'id'=>'verifyCode'
    ],
    'imageOptions'=>[
        //image的Html属性
        'class'=>'imagecode',
        'alt'=>'点击图片刷新'
    ]
]);?>
<?=Html::submitButton("提交",['class'=>'submit'])?>
<?=Html::endForm();?>

 

转载于:https://www.cnblogs.com/hsd1727728211/p/5913407.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值