3
* @link https://www.yiiframework.com/
4
* @copyright Copyright (c) 2008 Yii Software LLC
5
* @license https://www.yiiframework.com/license/
11
use yii\base\InvalidConfigException;
13
use yii\validators\ValidationAsset;
14
use yii\validators\Validator;
17
* CaptchaValidator validates that the attribute value is the same as the verification code displayed in the CAPTCHA.
19
* CaptchaValidator should be used together with [[CaptchaAction]].
21
* Note that once CAPTCHA validation succeeds, a new CAPTCHA will be generated automatically. As a result,
22
* CAPTCHA validation should not be used in AJAX validation mode because it may fail the validation
23
* even if a user enters the same code as shown in the CAPTCHA image which is actually different from the latest CAPTCHA code.
25
* @author Qiang Xue <qiang.xue@gmail.com>
28
class CaptchaValidator extends Validator
31
* @var bool whether to skip this validator if the input is empty.
33
public $skipOnEmpty = false;
35
* @var bool whether the comparison is case sensitive. Defaults to false.
37
public $caseSensitive = false;
39
* @var string the route of the controller action that renders the CAPTCHA image.
41
public $captchaAction = 'site/captcha';
47
public function init()
50
if ($this->message === null) {
51
$this->message = Yii::t('yii', 'The verification code is incorrect.');
58
protected function validateValue($value)
60
$captcha = $this->createCaptchaAction();
61
$valid = !is_array($value) && $captcha->validate($value, $this->caseSensitive);
63
return $valid ? null : [$this->message, []];
67
* Creates the CAPTCHA action object from the route specified by [[captchaAction]].
68
* @return \yii\captcha\CaptchaAction the action object
69
* @throws InvalidConfigException
71
public function createCaptchaAction()
73
$ca = Yii::$app->createController($this->captchaAction);
75
/* @var $controller \yii\base\Controller */
76
list($controller, $actionID) = $ca;
77
$action = $controller->createAction($actionID);
78
if ($action !== null) {
82
throw new InvalidConfigException('Invalid CAPTCHA action ID: ' . $this->captchaAction);
88
public function clientValidateAttribute($model, $attribute, $view)
90
ValidationAsset::register($view);
91
$options = $this->getClientOptions($model, $attribute);
93
return 'yii.validation.captcha(value, messages, ' . Json::htmlEncode($options) . ');';
99
public function getClientOptions($model, $attribute)
101
$captcha = $this->createCaptchaAction();
102
$code = $captcha->getVerifyCode(false);
103
$hash = $captcha->generateValidationHash($this->caseSensitive ? $code : strtolower($code));
106
'hashKey' => 'yiiCaptcha/' . $captcha->getUniqueId(),
107
'caseSensitive' => $this->caseSensitive,
108
'message' => Yii::$app->getI18n()->format($this->message, [
109
'attribute' => $model->getAttributeLabel($attribute),
110
], Yii::$app->language),
112
if ($this->skipOnEmpty) {
113
$options['skipOnEmpty'] = 1;