Repeat Password does not work in Yii2
Asked Answered
C

2

20

I have written rules in the model as:

    public $password_repeat;

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        ....
        ....  
        ['password', 'required'],
        ['password', 'string', 'min' => 6],
        ['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
    ];
}

If I use different password in Password and Password Repeat field, it gives error. So, that's mean it works. But problem is that, it does not give any error if Password Repeat field is empty.

Catechetical answered 11/3, 2015 at 6:1 Comment(1)
you need to mention required with repeat password like ['password_repeat', 'required'],Marmara
B
37

Add a required tag for password_repeat as well. Shown below

return [
        ....  
        ['password', 'required'],
        ['password', 'string', 'min' => 6],
        ['password_repeat', 'required'],
        ['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
    ];
Burt answered 11/3, 2015 at 6:4 Comment(2)
We need not to use required in Yii.1.*. Can you tell me why we need to use in Yii2?Catechetical
Yii and Yii2 have a lot of undocumented differences due to yii2 being built independently from scratch. This is just one of them.Burt
R
13

Another approach is to set the $skipOnEmpty variable to false:

return [
....  
    ['password', 'required'],
    ['password', 'string', 'min' => 6],
    ['password_repeat', 'compare', 'compareAttribute'=>'password', 'skipOnEmpty' => false, 'message'=>"Passwords don't match"],
];

This has the benefit of allowing you to only make the repeat password field required if password has a value in it too.

Rhynd answered 21/10, 2015 at 9:17 Comment(1)
brilliant - thank you. For anybody else trying this, you need to add a public variable to the model otherwise the form will declare an error. I.e.: public $password_repeatBraiding

© 2022 - 2024 — McMap. All rights reserved.