10

I wonder if it is possible with CakePHP validation rules to validate a field depending on another.

I have been reading the documentation about custom validation rules but the $check param only contains the value of the current field to validate.

For example. I would like to define the verify_password field as required only if the new_password field is not empty. (in case

I could do it with Javascript anyway but i wonder if it is possible to do it directly with CakePHP.

Alvaro
  • 37,936
  • 23
  • 138
  • 304

1 Answers1

14

When you validate data on a model, the data is already set(). This means that you can access it on the model's $data property. The example below checks the field we're validating to make sure it's the same as some other field defined in the validation rules (such as a password confirm field).

The validation rule would look something like this:

var $validate = array(
    'password' => array(            
        'minLength' => array(
            'rule' => array('minLength', 6),
            'message' => 'Your password must be at least 6 characters long.'
        ),
        'notempty' => array(
            'rule' => 'notEmpty',
            'message' => 'Please fill in the required field.'
        )
    ),
    'confirm_password' => array(
        'identical' => array(
            'rule' => array('identicalFieldValues', 'password'),
            'message' => 'Password confirmation does not match password.'
        )
    )
);

Our validation function then looks at the passed field's data (confirm_password) and compares it against he one we defined in the rule (passed to $compareFiled).

function identicalFieldValues(&$data, $compareField) {
    // $data array is passed using the form field name as the key
    // so let's just get the field name to compare
    $value = array_values($data);
    $comparewithvalue = $value[0];
    return ($this->data[$this->name][$compareField] == $comparewithvalue);
}

This is a simple example, but you could do anything you want with $this->data.

The example in your post might look something like this:

function requireNotEmpty(&$data, $shouldNotBeEmpty) {
    return !empty($this->data[$this->name][$shouldNotBeEmpty]);
}

And the rule:

var $validate = array(
  'verify_password' => array(
    'rule' => array('requireNotEmpty', 'password')
  )
);
jeremyharris
  • 7,735
  • 19
  • 31
  • Thanks for the explanation :) – Alvaro Jan 08 '13 at 14:58
  • 1
    In CakePHP 2.4 it doesn't seem like you can pass by reference to the function, it didn't seem to work for me, but using the example in the docs and changing it to $check worked. – mtpultz Sep 14 '15 at 04:21