CakePHP 3 - Compare passwords

TMoraes picture TMoraes · Feb 9, 2015 · Viewed 7.8k times · Source

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?

Answer

ndm picture ndm · Feb 9, 2015

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']
    ]
]);