小白小 2016-05-05 15:43:05 13290次浏览 8条评论 12 4 0

几天前开始做验证码,我之前是学Thinkphp的,到了这里感觉很没有头绪,然后上网找,找了半天都只是添加,愁死了。都没有验证,这里给大家补齐。还有人提到了--刷新页面验证码不变,我查了好久, 终于在自己家里看到了这个文章,谢谢


1. 添加验证码第一步:添加模型层代码,名字我就起了个Check

<?php
 namespace app\models;
 use Yii;
 use yii\base\Model;
 
 class Check extends Model
 {
     public $verifyCode;
     public function rules()
     {
         return [
             ['verifyCode', 'captcha','message'=>'验证码输入错误了,傻是不是?'],
         ];
     }

return里面的验证部分采用的内部验证,验证方式是captcha。

public function attributeLabels()
    {
        return [
            'verifyCode' => '请在右面输入验证码  懂不?',
        ];
    }
}
?>

第一步就完成了。开始第二步,建一个控制器

<?php
namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\models\Check;

	class PokpetsController extends Controller{
		public function actions(){
        	return [
            	'error' => [
                	'class' => 'yii\web\ErrorAction',
            	],
            	'captcha' => [
                	'class' => 'yii\captcha\CaptchaAction',
                			'maxLength'=>4,
                				'minLength'=>4,
            	],
        	];
    	}


actions里面还可以定义一些验证码的属性,我只定义了长度,还可以定义背景啦什么的。

public function actionNobody(){
        	$model = new Check();
        	if ($model->load(Yii::$app->request->post()) && $model->validate()){
            	return $this->refresh();
        	}
        	return $this->render('nobody',[
            	'model'=>$model,
        	]);
    	}
	}

?>

终于到了最后一步了,添加视图。注意文件名字,我的控制器是Pokpets
so 视图应该在Pokpets下的nobody.php。

<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;

?>
<div class="site-contact">
                <?php $form = ActiveForm::begin(); ?>

                    <?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
                        'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
                    ]) ?>

                    <div class="form-group">
                        <?= Html::submitButton('验证一下', ['class' => 'btn btn-primary']) ?>
                    </div>

                <?php ActiveForm::end(); ?>
</div>
?>


好嘞。 问题总结1.刷新页面更改验证码。在此再次感谢作者的总结。原文刷新页面且验证码变化的出处把false修改为true 还有问题的留言。。。以后会有修改**

觉得很赞
您需要登录后才可以评论。登录 | 立即注册