Yii password repeat field

12,183

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;
Share:
12,183
Most Wanted
Author by

Most Wanted

Want to be as Amelia Earhart.

Updated on June 13, 2022

Comments

  • Most Wanted
    Most Wanted almost 2 years

    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?

  • acorncom
    acorncom over 11 years
    One gotcha about your current setup is if the user is trying to update their password at a later date. But other than that, looks good.
  • Brett Gregson
    Brett Gregson over 11 years
    Well generally you would probably ask the user to input their password twice if they were updating. I did account for this with the scenario anyway ($model = new MyModel('create');)
  • Stefano Mtangoo
    Stefano Mtangoo over 10 years
    You can use sceario name as update which is default each time Yii creates AR model. and so your model becomes $model = new MyModel;
  • Tahir Yasin
    Tahir Yasin almost 10 years
  • Ferdinand Balbin
    Ferdinand Balbin over 9 years
    in my case the confirm password field value will also be inserted to database causing duplicate error. How to not include the confirm password value to be submitted or to be saved in the database?
  • Brett Gregson
    Brett Gregson about 6 years