Yii密码重复字段 [英] Yii password repeat field

查看:94
本文介绍了Yii密码重复字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建和更新用户时,我希望基于Yii的Web应用程序中的密码重复字段.创建时,我希望这两个字段都是必需的,并且在更新时,用户可以将这些字段保留为空(密码相同)或输入新密码并进行确认.我如何点它?

I want password repeat field in my web-application based on Yii when create and update user. When create I want both fields to be required and when update, user can left these fields empty(password will be the same) or enter new password and confirm it. How can I dot it?

推荐答案

首先,您需要在模型中创建一个新属性(在本示例中,我们将其称为 repeatpassword ):

First up, you need to create a new attribute in your model (in this example we call it repeatpassword):

class MyModel extends CActiveRecord{
    public $repeatpassword;
    ...

接下来,您需要定义一个规则以确保其与您现有的密码属性相匹配:

Next, you need to define a rule to ensure it matches your existing password attribute :

    public function rules() {
            return array(
                array('password', 'length', 'max'=>250),
                array('repeatpassword', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match"),
                ...
            );
    }

现在,当创建新模型时,除非密码和 repeatpassword 属性匹配,否则该模型将无法验证.如您所述,创建新记录很好,但是您不想在更新上验证匹配的密码.要创建此功能,我们可以使用模型方案

Now, when a new model is created, the model will not validate unless the password and repeatpassword attributes match. As you mentioned, this is fine for creating a new record, but you don't want to validate the matched password on the update. To create this functionality, we can use model scenarios

我们只是简单地更改了 repeatpassword 规则(如上所示)以添加其他参数:

We simply change the repeatpassword rule as seen above to have an additional parmanter:

...
array('repeatpassword', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match",'on'=>'create'),
...

现在剩下要做的就是在为create函数声明模型时使用:

All that is left to do now, is when declaring your model on for the create function, use:

$model = new MyModel('create');

不是正常的:

$model = new MyModel;

这篇关于Yii密码重复字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆