这篇文章主要介绍yii2验证码样式的设置方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
yii2验证码样式如何设置
第一步,控制器:
在任意controller里面重写方法
public function actions()
{ return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'backColor' => 0x000000,//背景颜色
'maxLength' => 6, //最大显示个数
'minLength' => 5,//最少显示个数
'padding' => 5,//间距
'height' => 40,//高度
'width' => 130, //宽度
'foreColor' => 0xffffff, //字体颜色
'offset' => 4, //设置字符偏移量 有效果
], ];
}
第二步,表单模型:
这里只给出验证码相关的部分。
相关文章教程推荐:yii教程
class ContactForm extends Model{
public $verifyCode;
public function rules(){
return [
['verifyCode', 'required'],
['verifyCode', 'captcha'],
];
}
}
验证规则里面验证码的验证器是captcha
。
第三步,视图:
用ActiveForm生成对应字段。
captchaAction
参数指定第一步是在写在哪里的,默认是site
里面。
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
验证码,生成和验证的整个流程就完成了。
以上是生成验证码的流程,因为验证码数字是在代码中写死的,如果我们需要数字的话,那该怎么办呢?
很好办,我们可以自己写个类来继承CaptchaAction,重写generateVerifyCode方法,例子:
namespace yii\captcha;
class Newcaptcha extends CaptchaAction
{
protected function generateVerifyCode()
{
if ($this->minLength > $this->maxLength) {
$this->maxLength = $this->minLength;
}
if ($this->minLength < 3) {
$this->minLength = 3;
}
if ($this->maxLength > 20) {
$this->maxLength = 20;
}
$length = mt_rand($this->minLength, $this->maxLength);
$letters = '1234567890123456789012';
$vowels = 'aeiou';
$code = '';
for ($i = 0; $i < $length; ++$i) {
if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
$code .= $vowels[mt_rand(0, 4)];
} else {
$code .= $letters[mt_rand(0, 20)];
}
}
return $code;
}
}
生成类文件成功。
然后再更改控制器的配置
'captcha' => [
'class' => 'yii\captcha\Newcaptcha',
'maxLength' => 5,
'minLength' =>5
],
以上是“yii2验证码样式的设置方法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。