[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();?>

 

posted @ 2016-09-27 16:39  mokal同学  阅读(288)  评论(0编辑  收藏  举报