CakePHP 3.x
我想做我的验证码自定义验证.但我无法访问会话.
$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;
public function validationLogin(Validator $validator,$customParameter) { //bla bla }
我用的是:http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules
您可以将Session数据作为验证函数的参数传递
原文链接:https://www.f2er.com/php/137937.html// 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',[ 'rule' => function ($value,$context) use ($sessionData) { if ($sessionData != $value){ return false; } return true; },'message' => 'error securty code' ]); return $validator; }
编辑:你可以从模型访问会话,但这不是一个好习惯,你最好避免它.而是将其从控制器传递,如上例所示
// In model use Cake\Network\Session; $session = new Session(); $sessionData = $session->read('captcha');