CakePHP自定义验证规则消息

5

我有一个自定义验证规则,用于检查两个输入的密码是否相同,如果不相同,我希望有一条消息提示"密码不匹配"。

这个规则是有效的,但是当密码不匹配时,它只会显示普通的错误消息,这是怎么回事?

var $validate=array(
        'passwd2' => array('rule' => 'alphanumeric',
                        'rule' => 'confirmPassword',
                        'required' => true,
                        'allowEmpty'=>false));

function confirmPassword($data)
{
    $valid = false;
    if ( Security::hash(Configure::read('Security.salt') .$data['passwd2']) == $this->data['User']['passwd'])
    {
        $valid = true;
        $this->invalidate('passwd2', 'Passwords do not match');
    }
    return $valid;
}

它说“该字段不能为空”

编辑:

奇怪的是,如果我留空一个密码字段,两个错误消息都会显示“该字段不能为空”

但是,如果我在两个字段中都输入了内容,则会正确地显示“密码不匹配”

3个回答

6
我认为您把它弄复杂了。这是我的做法:
    // In the model
    public $validate = array(
        'password' => array(
            'minLength' => array(
                'rule' => array('minLength', '8')
            ),
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'required' => true
            )
        ),
        'confirm_password' => array(
            'minLength' => array(
                'rule' => array('minLength', '8'),
                'required' => true
            ),
            'notEmpty' => array(
                'rule' => 'notEmpty'
            ),
            'comparePasswords' => array(
                'rule' => 'comparePasswords' // Protected function below
            ),
        )
    );
    protected function comparePasswords($field = null){
        return (Security::hash($field['confirm_password'], null, true) === $this->data['User']['password']);
    }

// In the view
echo $form->input('confirm_password', array(
    'label' => __('Password', true),
    'type' => 'password',
    'error' => array(
        'comparePasswords' => __('Typed passwords did not match.', true),
        'minLength' => __('The password should be at least 8 characters long.', true),
        'notEmpty' => __('The password must not be empty.', true)
    )
));
echo $form->input('password', array(
    'label' => __('Repeat Password', true)
));

哦,我不知道你可以在表单助手中将错误消息指定为选项,这简化了很多事情! - Razor Storm
它在食谱中 - http://book.cakephp.org/view/1401/options-error。 请注意,“confirm_password”和“password”字段的标签被交换。 - bancer

3

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接