Validate a field if other field changes


#1

Hello,

I want to apply a validation rule only if other field has been changed. In the Controller I can see if one field are changed looking at dirty array, but I can’t found how to do that in the Table. I want to validate the typical “password repeat situation”, where the validation of the password_repeat field only is needed if the password field has been changed:

$validator
    ->scalar('password')
    ->requirePresence('password')
    ->notEmpty('password');

$validator
    ->add('password_repeat', 'comparePasswords', [
        'rule' => ['compareWith', 'password'],
        'message' => __('Different password repeat'),
        'on' => function ($context) {
            // Some code to detect if the password field are changed
            return true;
        }
    ]);

Can you give me some tip?

Thanks in advance.


#2

What I do is leaving the password filed empty by default. So if there is a password there should be a password confirmation and they should be the same.

So if I have a password value I handle it as changed.

Side note: if you want higher security you should use 3 inputs: current password, new password and new password confirmation. First you check if the old password match and than do the change.


#3

On the other hand using a plugin like CakeDC/users solves most of the things without any coding.


#4

Thanks for the tip, rrd. I going to think about your suggestions (including the CakeDC plugin).


#5

I use this plugin for many of my projects. Handy, fast reliable and extendable.