关闭

yii2框架-yii2的rules验证(七)

标签: yii2rules
3037人阅读 评论(0) 收藏 举报
分类:
yii2的验证规则是一个非常实用而且高效安全的验证功能,下面是我自己的一些总结
在一个model里,继承ActiveRecord,重写覆盖原来的rules(),同时可以 启动场景的功能,重新覆盖scenarios()函数


model模型User.php:

namespace app\models;
use Yii;
use yii\web\IdentityInterface;
use yii\db\ActiveRecord;
use yii\captcha\Captcha;

class User extends ActiveRecord {

	//定义好属性,因为在mysql的表里没有这些字段,所以需要用到就得自定义
	//整个model的属性,其实还包括mysql的字段,ActiveRecord已经帮我们完成,所以无需定义
	public $verifyCode;
    public $password_compare;

     /**
     * @inheritdoc
    */
    public function rules()
    {
        return [
            //注册时必须字段,在register,和savede场景中都必须要
            [['useraccount', 'username', 'password'],'required','on'=>['register','save']],

            //任何场景都需要验证
            ['useraccount','string','length' =>[7,12]],

            /**验证是否唯一,即用户名是否已注册,在save场景中,这个动作由前端表单的设置'enableAjaxValidation'=>true来ajax异步触发,在控制器的save中要执行以下的代码:
            	$model->load($_POST);

		  if (Yii::$app->request->isAjax) {

		   	Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

		   	return \yii\bootstrap\ActiveForm::validate($model); 
		  }
            */
            ['useraccount', 'unique', 'targetClass'=>self::className(), 'message' => '此用户名已经被使用','on'=>'save'],


            //登录时字段必须
            [['useraccount','password'],'required','on'=>['login','dologin']],


            //密码验证,内联validatePassword的函数名进行验证
            ['password','validatePassword','skipOnEmpty'=>false,'on'=>['dologin']],

            //再次确认密码
            ['password_compare','required','on'=>'register'],

            //再次确认密码和密码对比
            ['password_compare', 'compare', 'compareAttribute' => 'password','message' => '两次密码不一致','on'=>'register'],

            /**验证码验证,在登录场景中,captchaAction的要设置正确,在user控制器中的公共actions中定义
            	public function actions()
		{
			return [
			  'captcha' => [
			      'class' => 'yii\captcha\CaptchaAction',
			      'maxLength' => 5,
		              'minLength' => 5,
			      'height'=>30,
			      'backColor'=>0xFE2341,
			     'offset'=>2
			   ],
	                ];
		}
            */
            ['verifyCode','captcha','captchaAction'=>'user/captcha','on'=>['login']]

        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
    	
    	//各个场景的活动属性
        $scenarios['register'] = ['useraccount', 'username', 'password','password_compare'];
        $scenarios['save'] = ['useraccount', 'username', 'password'];
        $scenarios['login'] = ['useraccount','password','verifyCode'];
        $scenarios['dologin'] = ['useraccount','password'];

        return $scenarios;
    
    }

    //这里是一些其他的登录认证函数..........
    

}
controller控制器UserController.php:

public function actions()
		{
		    return [
		         'captcha' => [
		              'class' => 'yii\captcha\CaptchaAction',
		              'maxLength' => 5,
		              'minLength' => 5,
		              'height'=>30,
		              'backColor'=>0xFE2341,
		              'offset'=>2
		         ],
		     ];
		}


	public function actionRegister() {

			$model = new User();
			$model->setScenario('register');

			$id = Yii::$app->user->id;
			// var_dump($id);

			return $this->render('register',['model' => $model]);
		}

	public function actionSave() {

		$model = new User();

		$model->setScenario('save');

		$model->load($_POST);

  		if (Yii::$app->request->isAjax) {

   			Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

   			return \yii\bootstrap\ActiveForm::validate($model); 
  		}

		$account = Yii::$app->request->post('User')['useraccount'];

		$model->load(Yii::$app->request->post());

		$model->authkey = md5($account);

		$model->accesstoken = md5($account);

		$model->password = md5(Yii::$app->request->post('User')['password']);

		$result = $model->save();
		
		if($result) {
			return $this->redirect(['index']);
		}
	}
view的视图register.php:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<style type="text/css">
    div.required label:before {
    content: " *";
    color: red;
}
</style>

<div class="register row" >
    <div class="col-lg-3">
    	<?php $form = ActiveForm::begin(['action' => ['user/save'],'enableAjaxValidation'=>true,'method'=>'post','options' =>['data-name'=>'yii','class'=>'form-horizontal']]); ?>
        
        <?= $form->field($model, 'useraccount',[
            'template'=>"<span class='glyphicon glyphicon-user'></span>{label}\n{input}\n{error}"

        ])->textInput(['placeholder' =>'请输入用户账号'])->label('用户账号') ?>

        <?= $form->field($model, 'username')->textInput()->label('用户名称') ?>

        <?= $form->field($model, 'password')->passwordInput()->label('密码') ?>

        <?= $form->field($model, 'password_compare')->passwordInput()->label('确认密码') ?>
        
        <?= Html::submitButton('注册', ['class'=>'btn btn-mod btn-primary','name' =>'submit-button']) ?>
        
        <?php  ActiveForm::end(); ?>
    </div>
</div>




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:174606次
    • 积分:2841
    • 等级:
    • 排名:第12554名
    • 原创:98篇
    • 转载:45篇
    • 译文:1篇
    • 评论:35条
    最新评论