9

Cakephp 3.x

I want to do my captcha custom validation. But I can not access a session.

$validator->notEmpty('securityCode', __('not empty message'))
    ->add('securityCode','custom', 
        ['rule' => function ($value, $context) use ($extra) {
            if($this->request->Session()->read('captcha') != $value) {
                return false;
            }
            return true;
        }, 'message' => 'error security code']);
 return $validator;

or can I my custom validation function give custom parameter?

public function validationLogin(Validator $validator, $customParameter)
{ //bla bla }

I use: http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules

powtac
  • 40,542
  • 28
  • 115
  • 170
Sinan Bay
  • 171
  • 4
  • 12

2 Answers2

11

You can pass Session data as parameter of validation function like this

// In Controller
$sessionData = $this->request->Session()->read('captcha');
$validator = $this->{YourModel}->validationLogin(new Validator(), $sessionData);

$errors = $validator->errors($this->request->data());
if (!empty($errors)) {
    // Captcha validation failed
}


// In Model
public function validationLogin(Validator $validator, $sessionData)
{
    $validator
        ->notEmpty('securityCode', __('not empty message'))
        ->add('securityCode', 'custom', [
            'rule' => function ($value, $context) use ($sessionData) {
                if ($sessionData != $value){
                    return false;
                }
                return true;
            },
            'message' => 'error securty code'
        ]);

        return $validator;
}

Edit: you can access session from model, but it is not a good practise and you better avoid it. Instead rather pass it from controller as in example above

// In model
use Cake\Network\Session;
$session = new Session();
$sessionData = $session->read('captcha');
5

For CakePHP 3: at the top of your Model class add

use Cake\Network\Session;

and at the point where you want to have to access the session add

$this->session = new Session();
$messages = $this->session->read('captcha'); // Example for the default flash messages

To set a flash message in the model use

$this->session = new Session();
$messages      = $this->session->read('Flash.flash');
$messages[]    = ['message' => 'YOUR FLASH MESSAGE', 'key' => 'flash', 'element' => 'Flash/default', 'params' => []];
$this->session->write('Flash.flash', $messages);
powtac
  • 40,542
  • 28
  • 115
  • 170
  • 2
    I know it's been four years, but I stumbled upon this looking for the answer, so if everyone else has - do not do this. Calling new Session in model can mess up with Auth component rsuting in "session already started" error. – Michał Skrzypek Mar 09 '20 at 08:28