zoukankan      html  css  js  c++  java
  • Yii实现Password Repeat Validate Rule

    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的验证了。

  • 相关阅读:
    gcd
    Kuglarz
    三分题解
    杜教筛
    第一组dp解题报告
    dp总结1
    cf-BitwiseXor
    6.6总结
    图论总结
    CF1309总结
  • 原文地址:https://www.cnblogs.com/xiongsd/p/3060607.html
Copyright © 2011-2022 走看看