微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

本文为大家分享了yii2.0实现验证用户名与邮箱功能的相关代码,具体内容如下

视图signup.PHP代码

rush:PHP;"> / @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">

title) ?>

Please fill out the following fields to signup:

<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')->password<a href="https://www.jb51.cc/tag/input/" target="_blank" class="keywords">input()</a> ?>
<?= $form->field($model,'password_compare')->password<a href="https://www.jb51.cc/tag/input/" target="_blank" class="keywords">input()</a> ?>

<div class="form-group"&gt;
 <?= Html::submitButton('Signup',['class' => 'btn btn-primary','name' => 'signup-button']) ?>
</div>

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

控制器SiteController.PHP

$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

/**

  • 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'],'unique','targetClass' => '\common\models\User','message' => '用户名已存在.'],'string','min' => 2,'max' => 255],['email','email'],'message' => '邮箱名已存在.'],[['password','password_compare'],'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验证功能

原文地址:https://www.jb51.cc/php/20715.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐