【发布时间】:2015-02-09 02:22:21
【问题描述】:
我有两个字段“密码”(该字段在数据库中)和confirm_password(该字段不在数据库中)
好吧,我需要比较密码 == confirm_password.. 但我不知道为“confirm_password”创建自定义验证...是否需要在数据库中包含此字段?
我该怎么做?
【问题讨论】:
标签: php cakephp cakephp-3.0
我有两个字段“密码”(该字段在数据库中)和confirm_password(该字段不在数据库中)
好吧,我需要比较密码 == confirm_password.. 但我不知道为“confirm_password”创建自定义验证...是否需要在数据库中包含此字段?
我该怎么做?
【问题讨论】:
标签: php cakephp cakephp-3.0
通常,您可以通过$context 参数访问custom validation rule 中的所有数据,这些数据存储在data 键中,即$context['data']['confirm_password'],然后您可以将其与当前字段值进行比较。
$validator->add('password', 'passwordsEqual', [
'rule' => function ($value, $context) {
return
isset($context['data']['confirm_password']) &&
$context['data']['confirm_password'] === $value;
}
]);
话虽如此,最近引入了 compareWith 验证规则,它正是这样做的。
https://github.com/cakephp/cakephp/pull/5813
$validator->add('password', [
'compare' => [
'rule' => ['compareWith', 'confirm_password']
]
]);
【讨论】:
confirm_password 字段添加相同的规则,然后与password 进行比较。
compareWith 在 CakePHP 2.x 中不可用
现在验证器类中有一个方法调用 sameAs,适用于 3.2 或更高版本。
$validator -> sameAs('password_match','password','Passwords not equal.');
见API
【讨论】:
我知道这是迟到的答案,但会对其他人有所帮助。
// Your password hash value (get from database )
$hash = '$2y$10$MC84b2abTpj3TgHbpcTh2OYW5sb2j7YHg.Rj/DWiUBKYRJ5./NaRi';
$plain_text = '123456'; // get from form and do not make hash. just use what user entred.
if (password_verify($plain_text, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
或
$hasher = new DefaultPasswordHasher();
$check = $hasher->check($plain_text,$hash); // it will return true/false
【讨论】: