Yii实现Password Repeat Validate Rule

本文介绍在Yii框架中实现密码重复验证的方法。通过在User模型中添加password_repeat属性,并在rules方法中定义验证规则,结合SiteController中的场景设置,以及视图文件中对应的字段输入,实现了密码的一致性校验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值