Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp Custom validation rule message

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"

like image 597
Razor Storm Avatar asked Oct 22 '10 09:10

Razor Storm


2 Answers

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)
));
like image 117
bancer Avatar answered Oct 08 '22 02:10

bancer


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

like image 29
Martz Avatar answered Oct 08 '22 03:10

Martz