本篇文章给大家分享的是有关利用yii2.0怎么实现一个用户名验证功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
视图signup.php代码:
<?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model \frontend\models\SignupForm */ $this->title = '注册'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-signup"> <h2><?= Html::encode($this->title) ?></h2> <p>Please fill out the following fields to signup:</p> <div class="row"> <div class="col-lg-5"> <?php $form = ActiveForm::begin([ 'id' => 'form-signup', 'enableAjaxValidation' => true, 'enableClientValidation' => true, ]); ?> <?= $form->field($model, 'username') ?> <?= $form->field($model, 'email') ?> <?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'password_compare')->passwordInput() ?> <div class="form-group"> <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> </div>
控制器SiteController.php
public function actionSignup() { $model = new SignupForm(); $model->load($_POST); if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return \yii\bootstrap\ActiveForm::validate($model); } if ($model->load(Yii::$app->request->post())) { if ($user = $model->signup()) { if (Yii::$app->getUser()->login($user)) { return $this->goHome(); } } } return $this->render('signup', [ 'model' => $model, ]); }
模型SignupForm.php
use common\models\User; use yii\base\Model; use Yii; /** * Signup form */ class SignupForm extends Model { public $username; public $email; public $password; public $password_compare; /** * @inheritdoc */ public function rules() { return [ ['username', 'filter', 'filter' => 'trim'], ['username', 'required'], ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => '用户名已存在.'], ['username', 'string', 'min' => 2, 'max' => 255], ['email', 'filter', 'filter' => 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => '邮箱名已存在.'], [['password', 'password_compare'], 'required'], [['password', 'password_compare'], 'string', 'min' => 6, 'max' => 16, 'message' => '{attribute}是6-16位数字或字母'], ['password_compare', 'compare', 'compareAttribute' => 'password', 'message' => '两次密码不一致'], ]; } /** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); if ($user->save()) { return $user; } } return null; } }
以上就是利用yii2.0怎么实现一个用户名验证功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。