码迷,mamicode.com
首页 > 其他好文 > 详细

YII2.0 验证表单

时间:2016-08-23 18:42:00      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

控制器代码

<?php
namespace app\modules\pub\controllers;
use Yii;
use backend\base\BaseController;
use backend\modules\pub\models\LoginForm;
use backend\modules\pub\models\RegisterForm;
class DefaultController extends BaseController{
    public $layout = false;
    public function actions(){
        return [
            // captcha action renders the CAPTCHA image displayed on the contact page
            ‘captcha‘=>[
                ‘class‘ => ‘yii\captcha\CaptchaAction‘,
                ‘backColor‘=>0xFFFFFF,  //背景颜色
                ‘minLength‘=>6,  //最短为4位
                ‘maxLength‘=>6,   //是长为4位
                ‘transparent‘=>true,  //显示为透明
                ‘testLimit‘=>0,
                ‘fixedVerifyCode‘ => YII_ENV_TEST ? ‘test‘ : null,
            ],
        ];
    }
    //登录
    public function actionIndex(){
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render(‘index‘, [
                ‘model‘ => $model,
            ]);
        }
    }
    //注册
    public function actionRegister(){
        $model = new RegisterForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->register()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }
        return $this->render(‘register‘, [
            ‘model‘ => $model,
        ]);
    }
}

模型代码

<?php
namespace backend\modules\pub\models;
use app\modules\pub\models\YiiUser;
use backend\models\CommonModel;
use Yii;
class RegisterForm extends CommonModel{
    public $username;
    public $password;
    public $password_rep;
    public $email;
    public $verifyCode;
    //验证规则
    public function rules(){
        return [
            //账号、密码、确认密码、邮箱、验证码必须
            [[‘username‘,‘password‘,‘password_rep‘,‘email‘,‘verifyCode‘],‘required‘],
            //账号只能是汉字/数字/下划线,不能包含空格
            [‘username‘,‘match‘,‘pattern‘=>‘/^[\x{4e00}-\x{9fa5}_a-zA-Z0-9]*$/‘],
            //用户名最大10位,最小3位
            [‘username‘,‘string‘,‘max‘=>16,‘min‘=>2],
            //用户名/邮箱唯一
            [‘username‘,‘unique‘,‘targetClass‘=>‘\backend\modules\pub\models\YiiUser‘,‘message‘=>‘账号已存在‘],
            [‘email‘,‘unique‘,‘targetClass‘=>‘\backend\modules\pub\models\YiiUser‘,‘message‘=>‘邮箱已被绑定‘],
            //去除空格
            [[‘username‘,‘email‘],‘trim‘],
            //密码最大16位,最小6位
            [‘password‘,‘string‘,‘max‘=>16,‘min‘=>6],
            //验证邮箱
            [‘email‘,‘email‘,‘message‘=>‘邮箱不规范‘],
            //验证两次密码是否一致
            [‘password_rep‘,‘compare‘,‘compareAttribute‘=>‘password‘,‘message‘=>‘两次密码不一致‘],
            //验证码
            [‘verifyCode‘, ‘captcha‘,‘captchaAction‘=>‘pub/default/captcha‘],
        ];
    }
    public function attributeLabels(){
        return [
            ‘username‘=>‘用户名‘,
            ‘password‘=>‘密码‘,
            ‘password_rep‘=>‘确认密码‘,
            ‘verifyCode‘=>‘验证码‘,
            ‘email‘=>‘邮箱‘,
        ];
    }
    public function register(){
        if ($this->validate()) {
            $user = new YiiUser();
            $user->username = $this->username;
            $user->email = $this->email;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            if ($user->save()) {
                return $user;
            }
        }
        return null;
    }
}

页面Form代码

<?php $form = ActiveForm::begin([
                    ‘id‘ => ‘form-signin‘,
                ]); ?>
                <!--<form id="form-signin" class="form-signin">-->
                <section>
                    <?= $form->field($model,‘username‘)->textInput([‘placeholder‘=>‘只能由汉字/数字/下划线组成,不能包含空格‘])->label(‘账号‘)?>
                    <!--<div class="input-group">
                            <?/*= $form->field($model,‘username‘)->label(‘账号‘)*/?>
                            <input type="text" class="form-control" name="username" placeholder="用户名">
                            <div class="input-group-addon"><i class="fa fa-user"></i></div>
                        </div>-->
                    <?= $form->field($model,‘password‘)->passwordInput([‘placeholder‘=>‘密码‘])->label(‘密码‘)?>
                    <?= $form->field($model,‘password_rep‘)->passwordInput([‘placeholder‘=>‘确认密码‘])->label(‘确认密码‘)?>
                    <?= $form->field($model,‘email‘)->textInput([‘placeholder‘=>‘邮箱‘])->label(‘邮箱‘)?>
                    <?= $form->field($model, ‘verifyCode‘)->label(‘验证码‘)->widget(Captcha::className(), [
                        ‘options‘=>[‘placeholder‘=>‘验证码‘],
                        ‘captchaAction‘ => ‘default/captcha‘,
                        ‘imageOptions‘=>[‘style‘=>‘margin-top:-5px;‘,],
                        ‘template‘ => ‘<div class="row"><div class="col-lg-6">{input}</div><div class="col-lg-6">{image}</div></div>‘,
                    ]) ?>
                    <!--<div class="input-group">
                        <input type="password" class="form-control" name="password" placeholder="密码">
                        <div class="input-group-addon"><i class="fa fa-key"></i></div>
                    </div>-->
                </section>
                <section class="controls">
                    <div class="checkbox check-transparent">
                        <!--<input type="checkbox" value="1" id="remember" checked>
                        <label for="remember">记住我</label>-->
                    </div>
                    <a href="#">忘记密码?</a>
                </section>
                <section class="log-in">
                    <?= Html::submitButton(‘注册‘, [‘class‘ => ‘btn btn-greensea‘]) ?>
                    <!--<button class="btn btn-greensea">登录</button>-->
                    <span>或</span>
                    <?= Html::a(‘登录‘,null,[‘href‘=>Url::toRoute(‘default/index‘),‘class‘=>‘btn btn-slategray‘]) ?>
                    <!--<button class="btn btn-slategray">创建一个新账号</button>-->
                </section>
                <!--</form>-->
                <?php ActiveForm::end(); ?>

YII2.0 验证表单

标签:

原文地址:http://www.cnblogs.com/wenxinphp/p/5800436.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!