Yii password repeat field

a 夏天 提交于 2019-12-08 16:49:43

问题


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?


回答1:


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"),
                ...
            );
    }

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

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'),
...

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

$model = new MyModel('create');

Instead of the normal:

$model = new MyModel;


来源:https://stackoverflow.com/questions/13363748/yii-password-repeat-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!