Yii2.0的自带的验证依赖于GD2或者ImageMagick扩展。
使用步骤如下:
第一步,控制器:
在任意controller里面重写方法
代码折叠,点击查看
<?php namespace frontend\controllers; use Yii; use app\models\login; use app\models\search\UserSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\captcha\CaptchaAction; /** * UserController implements the CRUD actions for User model. */ class LoginController extends Controller { public function actions() { return [ ‘error‘ => [ ‘class‘ => ‘yii\web\ErrorAction‘, ], ‘captcha‘ => [ ‘class‘ => ‘yii\captcha\CaptchaAction‘, ‘fixedVerifyCode‘ => YII_ENV_TEST ? ‘testme‘ : null, ‘backColor‘=>0x000000,//背景颜色 ‘maxLength‘ => 6, //最大显示个数 ‘minLength‘ => 5,//最少显示个数 ‘padding‘ => 5,//间距 ‘height‘=>40,//高度 ‘width‘ => 130, //宽度 ‘foreColor‘=>0xffffff, //字体颜色 ‘offset‘=>4, //设置字符偏移量 有效果 //‘controller‘=>‘login‘, //拥有这个动作的controller ], ]; } public function actionIndex() { $model=new Login; return $this->render(‘form‘,[‘model‘=>$model]); } }
第二步:模型层,
代码如下:
<?php namespace app\models; use Yii; use yii\base\Model; class Login extends Model { public $verifyCode; public $name; public $pwd; /** * @return array the validation rules. */ public function rules() { return [ // verifyCode needs to be entered correctly [‘verifyCode‘, ‘captcha‘,‘message‘=>‘验证码不正确‘], [[‘name‘,‘pwd‘],‘required‘,‘message‘=>‘{attribute}不能为空‘] ]; } /** * @return array customized attribute labels */ public function attributeLabels() { return [ ‘verifyCode‘ => ‘‘, ]; } }
最后views层表单:
代码如下:
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\captcha\Captcha; /* @var $this yii\web\View */ /* @var $model app\models\User */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="user-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, ‘name‘)->textInput([‘maxlength‘ => true])->label(‘姓名‘) ?> <?= $form->field($model, ‘pwd‘)->textInput([‘maxlength‘ => true])->label(‘密码‘) ?> <?= $form->field($model, ‘verifyCode‘)->widget(Captcha::className(), [ ‘template‘ => ‘<div class="row"><div class="col-lg-2">{input}</div><div class="col-lg-2">{image}</div></div>‘, ])->label(‘验证码‘) ?> <div class="form-group"> <?= Html::submitButton(‘提交‘, [‘class‘=>‘btn btn-primary‘,‘name‘ =>‘submit-button‘]) ?> <?= Html::resetButton(‘重置‘, [‘class‘=>‘btn btn-primary‘,‘name‘ =>‘submit-button‘]) ?> </div> <?php ActiveForm::end(); ?> </div>
经过以上步骤,验证码基本就可以使用了。
时间: 2024-10-27 04:31:48