views:

25

answers:

2

I have a custom validation rule to check if two passwords entered are the same, and if they arent I wish to have a message that says "Passwords do not match".

The rule works, however, when the passwords don't match it simply displays the normal error message, what's going on?

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;
}

It says "This field cannot be left blank"

EDIT:

The strange thing is, if I leave one of the password fields blank, both error messages say "This field cannot be left blank"

However, if I put something in both, then it correctly says "Passwords do not match"

+1  A: 

You should use the 'message' key in your $validate array to specify the message:

'message' => 'Your passwords do not match'

Further reading: http://book.cakephp.org/view/1143/Data-Validation

Martz
+1  A: 

I think you made it too complex. Here is how I do it:

    // 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)
));
bancer
Oh I didn't know you can specify error message as an option in the form helper, that simplifies things a lot!
Razor Storm
It is in the cookbook - http://book.cakephp.org/view/1401/options-error. Notice that labels for 'confirm_password' and 'password' fields are switched.
bancer