Password Confirm Validation CakePHP

12,476

two fields in view file

echo $this->Form->input('password');
echo $this->Form->input('repass');

Model file

<?php
class Post extends AppModel {
    public $validate = array(
        'repass' => array(
            'equaltofield' => array(
            'rule' => array('equaltofield','password'),
            'message' => 'Require the same value to password.',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            'on' => 'create', // Limit validation to 'create' or 'update' operations
            )
        )
    );

function equaltofield($check,$otherfield)
    {
        //get name of field
        $fname = '';
        foreach ($check as $key => $value){
            $fname = $key;
            break;
        }
        return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname];
    } 
}?>
Share:
12,476
TheLoy
Author by

TheLoy

Updated on June 11, 2022

Comments

  • TheLoy
    TheLoy almost 2 years

    I have searched far and wide, tried every trick in the book, but I still can't get my CakePHP application to perform simple Password Confirm validation. I've tried creating a custom validation rule like this:

    'passwordequal' => array('rule' => 'checkpasswords' , 'message' => 'Passwords Do Not Match')
    

    Then defined 'checkpasswords' like this:

    public function checkpasswords(){
    
        if(strcmp($this->data['User']['new_password'],$this->data['User']['confirm_password']) == 0 )
        {
            return true;
        }
        return false;
    }
    

    'new_password' and 'confirm_password' are the password input fields. This didn't work. Then I tried one in which I hashed the 'confirm_password'. That didn't work either. I have other 'rules' as well that are not being validated, like 'notempty', which I believe is one of the standard CakePHP rules. Can anybody please help. I know this question has been asked a few times but none of those solutions have worked for me. CakePHP documentation hasn't helped much either.

  • Garry
    Garry over 10 years
    I didn't know that $this->data can be used in model.I thought it is deprecated in 2.x versions. Thanks for that.
  • James Grey
    James Grey over 9 years
    When use echo $this->Form->input('repass');, your password display plain text. It is unacceptable. And better is use client side to validate first (javascript).
  • luizs81
    luizs81 about 9 years
    @DoNhuVy it can be easily fixed using array('type' => 'password') as a param when rendering the field in the view file. What is unacceptable is rely only in client side to make this kind of validation. You should always expect that some users will disable JavaScript to 'hack' your system.