Yii2.0的自带的验证依赖于GD2或者ImageMagick扩展。
使用步骤如下:
重写
yii\web\Controller::actions()方法,用ID"captcha"注册一个CaptchaAction类的action。在表单模型里面添加一个属性,用来保存用户输入的验证码字符串;这个属性的验证器是"captcha"。
在视图里面,把
yii\captcha\CaptchaWidget插入到表单里面。
第一步,控制器:
在任意controller里面重写方法
/**
* @inheritdoc
*/
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength' => 5,
'minLength' => 5
],
];
}第二步,表单模型:
假如是一个登陆表单。
这里只给出验证码相关的部分。
class LoginForm extends Model
{
public $verifyCode;
public function rules()
{
return [
['verifyCode', 'required'],
['verifyCode', 'captcha'],
];
}
}验证规则里面验证码的验证器是captcha。
第三步,视图:
用ActiveForm生成对应字段。
captchaAction参数指定第一步是在写在哪里的,默认是site里面。
<?= $form->field($model, 'verifyCode', [
'options' => ['class' => 'form-group form-group-lg'],
])->widget(Captcha::className(),[
'template' => "{image}",
'imageOptions' => ['alt' => '验证码'],
'captchaAction' => 'site/captcha',
]); ?>验证码,生成和验证的整个流程就完成了。
效果图,以登陆表单为例:

默认的验证码是纯字母,没有数字,而且这些可用字符是写死在代码里面的。
所以如果你要自定义里面的字符的话,可以自己新建个类,继承yii\captcha\CaptchaAction,重写generateVerifyCode方法就可以了。
本文链接:https://360us.net/article/17.html