cakephp表单验证密码比较

时间:2014-04-01 11:55:00

标签: forms validation cakephp passwords

我有重置密码的功能。 在我必须比较密码和password_confirm字段时,我得到一个奇怪的行为:

我的表格

echo $this->Form->hidden('tkn', array('value' => $tkn));
echo $this->Form->hidden('uid', array('value' => $uid));
echo $this->Form->input('password',array('type' => 'password', 'name' => 'data[Appuser][password]'));
echo $this->Form->input('password_confirm',array('type' => 'password', 'name' => 'data[Appuser][password_confirm]'));

我的模型验证:

var $validate = array(
        'password' => array(
            'rule'    => array('minLength', '6'),
            'message' => '{password} minLength 6!'
        ),
        'password_confirm' => array(
            'rule'    => array('equaltofield','password'),
            'message' => '{password_confirm} not equal!'
        ),
    );

function equaltofield($val1, $val2){
        return $this->data[$this->alias][key($val1)] == $this->data[$this->alias][$val2];
    }

我的控制器:

if($this->Appuser->save($this->data)){

                $this->Session->setFlash(__('Password has been updated'));

            }else{
                debug($this->Appuser->invalidFields());
            }

现在: 当我提交一个空表单时,我从invalidFields()

返回以下内容
array(
    'password' => '*****',
    'password_confirm' => array(
        (int) 0 => '{password_confirm} not equal!',
        (int) 1 => '{password_confirm} not equal!'
    )
)

问题1:为什么我没有得到消息,密码没有最小长度? 问题2:为什么我比较密码时会收到第二条消息两次?

当输入2个不同密码且最小长度时,我再次得到这个:

array(
    'password_confirm' => array(
        (int) 0 => '{password_confirm} not equal!',
        (int) 1 => '{password_confirm} not equal!'
    )
)

当调试($ this->数据)时,我也得到了这个(如果这有点帮助)

array(
    'Api' => array(
        'tkn' => '6837d241bf1076c3c55a95abbcfafa04dc19a33c',
        'uid' => '1'
    ),
    'Appuser' => array(
        'password' => '*****',
        'password_confirm' => 'asdfgh'
    )
)

关于我上面两个问题的任何想法? 在此先感谢!!

1 个答案:

答案 0 :(得分:0)

试试这个

var $validate = array(
        'password' => array(
            'rule'    => array('minLength', '6'),
            'message' => '{password} minLength 6!'
        ),
        'password_confirm' => array(
            'rule'    => 'equaltofield',
            'message' => '{password_confirm} not equal!'
        ),
    );

function equaltofield($data){
        return $this->data[$this->alias]['password'] == $this->data[$this->alias]['password_confirm'];
    }