yii2 验证码的使用

时间:2023-03-09 06:48:36
yii2 验证码的使用

@see  http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html

以下根据 MVC 模型的顺序来添加代码

1. model 层, 或者可以在默认的 LoginForm.php 上修改, 代码如下.

class LoginForm extends Model
{
// ......表示其他人码.
......
// 添加验证码属性字段
public $verifyCode;
...... public function rules()
{
return [
......
['verifyCode', 'captcha', 'captchaAction' => '/admin/login/captcha'],
......
];
}
}

如果使用默认 SiteController 控制器, 红包部分代码可不用填写, 如果使用其他比如我使用 http://my-domain.net/admin/login 控制器, 那红色部分就得添加了, 不然的话, 会提示

Exception (Invalid Configuration) 'yii\base\InvalidConfigException' with message 'Invalid CAPTCHA action ID: default/captcha'in E:\wamp\www\yii-application\vendor\yiisoft\yii2\captcha\CaptchaValidator.php:81

@see http://*.com/questions/28497432/yii2-invalid-captcha-action-id-in-module

2. view 层, 属性设置参考  http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html, 代码如下

        <?= $form
->field($model, 'verifyCode')
->label(false)
->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-6">{input}</div><div class="col-lg-3">{image}</div></div>',
'captchaAction' => 'login/captcha',
'options' => ['placeholder' => 'VerifyCode', 'class' => 'form-control'],
])
?>

3. 控制器里添加如下代码,  或者可以直接去默认 SiteController 里复制一份是一样的. 属性设置参考 http://www.yiiframework.com/doc-2.0/yii-captcha-captchaaction.html

    /**
* actions
*/
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength' => 5,
'minLength' => 5,
],
];
}