我在模型中写了规则:
public $password_repeat;
/**
* @inheritdoc
*/
public function rules()
{
return [
....
....
['password', 'required'],
['password', 'string', 'min' => 6],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
];
}
如果我在Password
和Password Repeat
字段中使用不同的密码,则会出错。所以,这意味着它有效。但问题是,如果Password Repeat
字段为空,则不会出现任何错误。
答案 0 :(得分:24)
也为password_repeat添加必需的标记。如下所示
return [
....
['password', 'required'],
['password', 'string', 'min' => 6],
['password_repeat', 'required'],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
];
答案 1 :(得分:8)
另一种方法是将$ skipOnEmpty变量设置为false:
return [
....
['password', 'required'],
['password', 'string', 'min' => 6],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'skipOnEmpty' => false, 'message'=>"Passwords don't match"],
];
这样做的好处是,如果密码中也包含值,则只允许重复密码字段。