CakePHP 3 - 比较密码
CakePHP 3 - Compare passwords
我有两个字段"password"(这个字段在数据库中)和confirm_password(这个字段不在数据库中)
好吧,我需要比较密码是否 == confirm_password.. 但我不知道要为 "confirm_password" 创建自定义验证...需要在数据库中包含此字段?
我该怎么做?
通常,您可以通过 $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']
]
]);
现在验证器 class 中有一个方法调用 sameAs,适用于版本 3.2 或更高版本。
$validator -> sameAs('password_match','password','Passwords not equal.');
见API
我知道这是迟到的答案,但会对其他人有所帮助。
// Your password hash value (get from database )
$hash = 'y$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
我有两个字段"password"(这个字段在数据库中)和confirm_password(这个字段不在数据库中)
好吧,我需要比较密码是否 == confirm_password.. 但我不知道要为 "confirm_password" 创建自定义验证...需要在数据库中包含此字段?
我该怎么做?
通常,您可以通过 $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']
]
]);
现在验证器 class 中有一个方法调用 sameAs,适用于版本 3.2 或更高版本。
$validator -> sameAs('password_match','password','Passwords not equal.');
见API
我知道这是迟到的答案,但会对其他人有所帮助。
// Your password hash value (get from database )
$hash = 'y$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