Create confirm password with validation in CakePHP


THIS IS FOR CAKE PHP 2.x

Creating a confirm password field with validation can be very easy with CakePHP. You can do this by modifying the User's model password validation.

In your User model password validation can be something like below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
public $validate = array(
        'username' => array(
                'notEmpty' => array(
                       'rule' => array('notEmpty'),
                 ),
         ),
        'password' => array(
               'notEmpty' => array(
                       'rule' => array('notEmpty'),
                      'message' => 'Please enter your password.',
               )
         )
);
?>

By default the above code is the structure for validating a password field if it is empty.

The 'password' is the field in your database, while the 'notEmpty' is just an alias for a certain rule. Now you can change it name you want but the default is 'notEmpty'. To add a custom rule we will add a new alias and we will call it matchPasswords so that the code above will be something like below.


public $validate = array(
        'username' => array(
                 'notEmpty' => array(
                 'rule' => array('notEmpty'),
                 ),
         ),
        'password' => array(
                 'notEmpty' => array(
                        'rule' => array('notEmpty'),
                        'message' => 'Please enter your password.',
                 ),
                'matchPasswords' => array(
                        'rule' => array('matchPasswords'),
                        'message' => 'Your passwords do not match!'
                 )
        )
);

public function matchPasswords($data){
      if ($data['password']==$this->data['User']['confirm_password']){
            return true;
       }
       $this->invalidate('confirm_password','Your passwords do not match!');
        return false;
}
Notice that we have created a certain rule name matchPasswords that will call a function outside our validation. The matchPasswords function will just simply take the data from the view which is the confirm_password input field and then compare it to the password field. If it matches then it will proceed otherwise it will bring a not equal password message.

That's it. Now in your User's view you can have something like below and your good to go!

<?php echo $this->Form->input('password'); ?>
<?php echo $this->Form->input('confirm_password',array('type'  =>  'password')); ?>


Labels: