Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP Validation depending on other field

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.

like image 795
Alvaro Avatar asked Jan 08 '13 14:01

Alvaro


1 Answers

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')
  )
);
like image 177
jeremyharris Avatar answered Sep 22 '22 20:09

jeremyharris