Yii2.0的自带的验证依赖于GD2或者ImageMagick扩展。
使用步骤如下:
-
重写yii\web\Controller::actions()方法,用ID"captcha"注册一个CaptchaAction类的action。
-
在表单模型里面添加一个属性,用来保存用户输入的验证码字符串;这个属性的验证器是"captcha"。
-
在视图里面,把yii\captcha\Captcha Widget插入到表单里面。
第一步,控制器:
在任意controller里面重写方法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/**
* @inheritdoc
*/
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength' => 5,
'minLength' => 5
],
];
}
|
第二步,表单模型:
假如是一个登陆表单。
这里只给出验证码相关的部分。
|
1
2
3
4
5
6
7
8
9
10
11
12
|
class LoginForm extends Model
{
public $verifyCode;
public function rules()
{
return [
['verifyCode', 'required'],
['verifyCode', 'captcha'],
];
}
}
|
验证规则里面验证码的验证器是captcha。
第三步,视图:
用ActiveForm生成对应字段。
|
1
2
3
4
5
6
|
<?= $form->field($model, 'verifyCode', [
'options' => ['class' => 'form-group form-group-lg'],
])->widget(Captcha::className(),[
'template' => "{image}",
'imageOptions' => ['alt' => '验证码'],
]); ?>
|
验证码,生成和验证的整个流程就完成了。
效果图,以登陆表单为例:
默认的验证码是纯字母,没有数字,而且这些可用字符是写死在代码里面的。
所以如果你要自定义里面的字符的话,可以自己新建个类,继承yii\captcha\CaptchaAction,重写generateVerifyCode方法就可以了。
转载于:https://my.oschina.net/tanwen/blog/484594