Shinomoto Asakura
Shinomoto Asakura

Reputation: 1542

CakePHP 3 - Compare passwords

I have two field "password" (This field is in the database) and confirm_password (This field is not in the database)

Well, I need to compare if password == confirm_password.. but I'm not knowing create a custom validation to "confirm_password"... Would need to have this field in the database?

How do I do?

Upvotes: 9

Views: 8382

Answers (3)

Yogesh Saroya
Yogesh Saroya

Reputation: 1515

I know it's late answer but will help to other.

// 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.';
}

OR

$hasher = new DefaultPasswordHasher();
$check = $hasher->check($plain_text,$hash); // it will return true/false

Upvotes: 0

Alimon Karim
Alimon Karim

Reputation: 4469

Now there has a method call sameAs in validator class, for version 3.2 or grater.

 $validator -> sameAs('password_match','password','Passwords not equal.');

see API

Upvotes: 7

ndm
ndm

Reputation: 60503

Generally you can access all data in a custom validation rule via the $context argument, where it's stored in the data key, ie $context['data']['confirm_password'], which you could then compare to the current fields value.

$validator->add('password', 'passwordsEqual', [
    'rule' => function ($value, $context) {
        return
            isset($context['data']['confirm_password']) &&
            $context['data']['confirm_password'] === $value;
    }
]);

That being said, recently a compareWith validation rule was introduced which does exactly that.

https://github.com/cakephp/cakephp/pull/5813

$validator->add('password', [
    'compare' => [
        'rule' => ['compareWith', 'confirm_password']
    ]
]);

Upvotes: 24

Related Questions