网络编程 
首页 > 网络编程 > 浏览文章

yii2.0实现验证用户名与邮箱功能

(编辑:jimmy 日期: 2024/9/17 浏览:3 次 )

本文为大家分享了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验证功能。

上一篇:php删除数组中重复元素的方法
下一篇:PHP内核探索之解释器的执行过程
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 SiteMap