你是否正在使用 AuthComponent?请注意它会对所有传入的密码字段进行哈希处理(但不包括“确认密码”字段,请通过debug($this->data)
检查),因此这些字段将永远不相同。请阅读手册并使用AuthComponent::password
进行检查。
话虽如此,以下是我使用的一些内容:
public $validate = array(
'password' => array(
'confirm' => array(
'rule' => array('password', 'password_control', 'confirm'),
'message' => 'Repeat password',
'last' => true
),
'length' => array(
'rule' => array('password', 'password_control', 'length'),
'message' => 'At least 6 characters'
)
),
'password_control' => array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
'message' => 'Repeat password'
)
)
);
public function password($data, $controlField, $test) {
if (!isset($this->data[$this->alias][$controlField])) {
trigger_error('Password control field not set.');
return false;
}
$field = key($data);
$password = current($data);
$controlPassword = $this->data[$this->alias][$controlField];
switch ($test) {
case 'confirm' :
if ($password !== Security::hash($controlPassword, null, true)) {
$this->invalidate($controlField, 'Repeat password');
return false;
}
return true;
case 'length' :
return strlen($controlPassword) >= 6;
default :
trigger_error("Unknown password test '$test'.");
}
}
以下是此方法不好的原因:
- 与表单紧密耦合,始终期望存在一个名为
password_control
的字段。如果您的数据中没有该字段,则需要使用字段白名单或禁用验证,例如:$this->User->save($this->data, true, array('field1', 'field2'))
。
- 手动散列密码的方式与 AuthComponent 相同(因为模型无法干净地访问组件)。如果更改了 AuthComponent 中使用的算法,则还需要在此处进行更改。
尽管如此,该方法仍然能够透明地验证并生成正确的错误消息,而无需在控制器中添加任何额外的代码。
$this->datadata
是否是你想要的?如果不是,那就是问题所在了。 - Stephenstrcmp
返回0
。但0
将被理解为false
,因此它会做与您预期的完全相反的事情。 - deceze