CakePHP validation rule to match field1 and field2

白昼怎懂夜的黑 提交于 2019-12-11 10:19:51

问题


I am making a password reset form, which contains two fields: password1 and password2. The user enters their new password and then re-types their new password again.

I'm not sure how to make a validation rule that will compare the two values from the fields and see if they're the same.


回答1:


if you are using Auth component then you need to hash the second password in the controller, because the password will be automatically hashed.

To compare 2 fields, you need to write a custom validation rule: http://bakery.cakephp.org/articles/aranworld/2008/01/14/using-equalto-validation-to-compare-two-form-fields (read the comments also, because the tutorial itself is kind of old)




回答2:


IMHO it's more trouble than worth to create a separate rule in this case. You could, if you want to code "pure" CakePHP, but it's easier to just compare the fields in the controller and invalidate one of them manually if they don't match:

if( $this->data[ 'User' ][ 'password1' ] != $this->data[ 'User' ][ 'password2' ] ) {
    $this->User->invalidate( 'password2', "The passwords don't match." );
}



回答3:


I just happen to have written a behavior for this 2 days ago: https://github.com/dereuromark/tools/blob/master/Model/Behavior/PasswordableBehavior.php

some sample code how to use it: http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/



来源:https://stackoverflow.com/questions/6792667/cakephp-validation-rule-to-match-field1-and-field2

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