Yii实现Password Repeat Validate Rule

在使用Yii时遇到这样的需求:在一个注册的页面输入两次密码,并验证两次输入是否一致。可是password的repeat的字段在数据库 并不存在。问题来了,如何创建一个password_repeat的属性,进行密码验证。最偷懒的方法就是利用yii自带的验证器。在这里记录下实现的方 法。

假设项目结构如下

protected/models/User.php

proteced/controllers/SiteController.php

protected/views/site/forgot.php

首先在User.php添加一个public的password_repeat属性,该属性会自动映射到rules中。注意on属性,是决定rule应用的场景,默认的场景是insert。在这里,我应用在forgot场景。

class User extends CActiveRecord
{
    public $password_repeat;
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            ...
            array('password_repeat', 'required' , 'on' => 'forgot'),
            array('password', 'compare', 'compareAttribute'=>'password_repeat' ,'on'=>'forgot'),
 
        );
    }
}

在SiteController.php中的actionForgot方法中,添加一个User的model。

public function actionForgotPassword(){
   $model = new User();
   //set current scenario
   $model->scenario = 'forgot';
   $User = Yii::app()->getRequest()->getParam('User');
   if($User){
      $model->attributes = $User;
      Helper::performAjaxValidation($model);
   ....
   }
   $this->render('forgot',array( 'model' => $model));
}
//Helper的ajax 验证方法,这个在默认生成的controller可以找到
static function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

在视图文件中forgot.php,添加password_repeat字段。

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'user-form',
    'enableAjaxValidation'=>true,
)); ?>
<ul>
<li>
        <?php echo $form->label($model,'password' , array( 'label' => 'Your New Password')); ?>
        <?php echo $form->passwordField($model,'password',array('size'=>32,'maxlength'=>32)); ?>
        <?php echo $form->error($model,'password'); ?>
    </li>
<li>
        <?php echo $form->labelEx($model,'password_repeat' , array( 'label' => 'Repeat Password')); ?>
        <?php echo $form->passwordField($model,'password_repeat',array('size'=>32,'maxlength'=>32)); ?>
        <?php echo $form->error($model,'password_repeat'); ?>
    </li>
</ul>

这样就实现了password的验证了。

不掉到水里,也永不知道自己有多大潜力!
原文地址:https://www.cnblogs.com/guolanzhu/p/3510209.html