CakePHP 3 - Compare passwords

做~自己de王妃 提交于 2019-12-21 04:42:35

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/28401893/cakephp-3-compare-passwords

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!