Reputation: 10061
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.
Upvotes: 20
Views: 20333
Reputation: 131
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.
Upvotes: 13
Reputation: 2497
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" ],
];
Upvotes: 37