19

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.

StreetCoder
  • 9,871
  • 9
  • 44
  • 62

2 Answers2

36

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" ],
    ];
arkoak
  • 2,437
  • 21
  • 35
  • We need not to use `required` in `Yii.1.*`. Can you tell me why we need to use in `Yii2`? – StreetCoder Mar 11 '15 at 06:07
  • Yii and Yii2 have a lot of undocumented differences due to yii2 being built independently from scratch. This is just one of them. – arkoak Mar 11 '15 at 06:10
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.

Tim Cummins
  • 131
  • 1
  • 2
  • 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_repeat – DrBorrow Oct 23 '16 at 20:36