富贵资源网 Design By www.hznty.com
本文为大家分享了yii2.0实现验证用户名与邮箱功能的相关代码,具体内容如下
视图signup.php代码:
<"site-signup"> <h1><"row"> <div class="col-lg-5"> <"form-group"> <"htmlcode">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验证功能。
富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com
暂无评论...