【发布时间】:2011-06-27 16:33:42
【问题描述】:
我有一个用户可以更改密码的页面。该表单包含 3 个字段:当前密码 (old_pass)、新密码 (pass) 和新密码确认 (pass_confirm)。问题是,这些字段没有经过验证,并且允许使用空白字段,尽管在模型定义中是禁止的。我不知道为什么,我在注册中有一个类似的表格,但它工作正常并显示这些字段的验证错误。
当我显示$this->User->validationErrors 时,数组为空。但是验证已经完成,我有用户名验证,它只在用户创建时有效,当我为所有User 表单(包括这个更改密码表单)激活它时,验证错误会正确显示在这里。
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php __('Change password'); ?></legend>
<?php
echo $this->Form->input('User.old_pass', array('type' => 'password',
'label' => __('Current password', true)));
echo $this->Form->input('User.pass', array( 'type' => 'password',
'label' => __('New password', true)));
echo $this->Form->input('User.pass_confirm', array('type' => 'password',
'label' => __('Repeat password', true)));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
与这些输入有关的validate 数组部分如下所示:
'pass' => array(
'required' => array(
'rule' => array('custom','/^.*[0-9].*$/i'),
'message'=>'Password must contain numbers',
'allowEmpty' => false
),
'length' => array(
'rule' => array('minLength',8),
'message' => 'Password must be at least 8 characters long')
),
'pass_confirm' => array(
/*'required' => array(
'rule' => 'notempty',
'message' => 'You have to confirm the password',
'allowEmpty' => false
),*/
'validate' => array(
'rule' => 'validate_password',
'message'=>'Your passwords don\'t match!' )
),
'old_pass' => array(
'length' => array(
'rule' => array('minLength',8),
'message' => 'Password must be at least 8 characters long'),
'allowEmpty' => false
)
function validate_password(){
//return false;
$passed=false;
if(isset($this->data['User']['pass_confirm']) && $this->data['User']['pass_confirm']!=''){
if ($this->data['User']['pass'] != $this->data['User']['pass_confirm']){
$this->invalidate('pass');
} else {
$passed=true;
}
}
return $passed;
}
顺便说一句,当我取消注释 validate_password 函数中的 return false; 行时,什么也没有发生,因此根本不会调用该方法。
我正在使用$this->User->save($data) 保存用户,$data 变量包含我想要以适当格式保存的数据并且工作正常。唯一的问题是这些字段没有被验证
编辑:
function change_password() {
$usr = $this->User->find('first', array(
'conditions'=> array(
'User.id' => $this->Auth->user('id')),
'recursive' => 0
));
if ($this->data) {
if ($this->Auth->password($this->data['User']['old_pass'])== $usr['User']['password']) {
$data = array(
'id' => $usr['User']['id'],
'password' => $this->Auth->password($this->data['User']['pass'])
);
if ($this->User->save($data)) {
$this->Session->setFlash(__('Password has been changed.', true));
} else {
debug($this->User->validationErrors);
$this->Session->setFlash(__('Password could not be saved, please try again later.', true));
}
} else {
$this->Session->setFlash(__('The password you entered as your current is not your current password.', true));
}
}
}
【问题讨论】:
-
你有没有找到这个问题的原因?我有完全相同的问题。奇怪的是,当我在保存失败后对控制器中的 validationErrors 进行调试调用时,change_password 操作显示保存了一些错误。但是,表单中仍然没有显示任何内容。
-
其实等一下。当您调用
save时,您只需传入用户的ID 和完整密码。你不要传入pass和pass_confirm。这可能是它没有针对任何东西进行验证的原因吗?
标签: php validation cakephp passwords cakephp-1.3