YII2.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(); ?>
时间: 2024-10-27 13:20:58

YII2.0 验证表单的相关文章

yii2.0 Activeform表单部分组件使用方法

文本框:textInput(); 密码框:passwordInput(); 单选框:radio(),radioList(); 复选框:checkbox(),checkboxList(); 下拉框:dropDownList(); 隐藏域:hiddenInput(); 文本域:textarea(['rows'=>3]); 文件上传:fileInput(); 提交按钮:submitButton(); 重置按钮:resetButtun(); <?php $form = ActiveForm::begi

yii2.0 Activeform表单部分组件使用方法 [ 2.0 版本 ]

文本框:textInput(); 密码框:passwordInput(); 单选框:radio(),radioList(); 复选框:checkbox(),checkboxList(); 下拉框:dropDownList(); 隐藏域:hiddenInput(); 文本域:textarea(['rows'=>3]); 文件上传:fileInput(); 提交按钮:submitButton(); 重置按钮:resetButtun(); <?php $form = ActiveForm::begi

ASP.NET 4.0 取消表单危险字符验证

/// <summary> /// ASP.NET4.0 表单验证类 /// </summary> public class FormRequestValidation : RequestValidator { public FormRequestValidation() { } protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSourc

js 验证表单 js提交验证类

js 验证表单 js提交验证类 附加:js验证radio是否选择 <script language="javascript">function checkform(obj){for(i=0;i<obj.oo.length;i++)         if(obj.oo[i].checked==true) return true; alert("请选择")return false; }</script><form id="f

jquery验证表单 提交表单

问题: jquery中使用submit提交按钮时,当return false后,依然会提交表单. 解决: 使用button按钮,而不是submit按钮 <script type="text/javascript" src="scripts/jquery-2.0.2.js"></script> <script type="text/javascript"> function check(){ var npassw

ExtJS学习笔记3:加载、提交和验证表单

加载数据 1.比较好用的设置form数据的方法: formPanel.getForm().setValues([{id: 'FirstName', value: 'Joe'}]); 其中id值为form中field的name属性值,value为要赋的值 2.通过对象赋值: Ext.define('Request', { extend: 'Ext.data.Model', fields: [ 'FirstName', 'LastName', 'EmailAddress', 'TelNumberCo

ajax验证表单元素规范正确与否 ajax展示加载数据库数据 ajax三级联动

一.ajax验证表单元素规范正确与否 以用ajax来验证用户名是否被占用为例 1创建表单元素<input type="text" id="t"> 2在js中用keyup事件来进行操作 3创建ajax格式和内容:格式: $.ajax({ url:"哪一个服务端处理器", data:{"自己起名",所需要传给处理器的数据}, type:"post", dataType:"json"

表单的属性和方法, 获取表单和表单的元素, 验证表单

表单的属性和方法 一. 表单字段的属性(id/name/value/form),这里用value属性来举例 上面的form属性代表获取表单字段的父级表单对象 1. 属性的获取         console.log(document.myform.username.value); 2. 属性的设置            document.myform.username.value="123"; 3. 获取表单字段的父级表单对象 console.log(document.myform.u

js验证表单大全

js验证表单大全1. 长度限制<script>function test() {if(document.a.b.value.length>50){alert("不能超过50个字符!");document.a.b.focus();return false;}}</script><form name=a onsubmit="return test()"><textarea name="b" cols=&