yii2验证码样式如何设置

yii2验证码样式如何设置

YII2验证码样式如何设置

第一步,控制器:

在任意controller里面重写方法

public function actions() {        return [         'captcha' => [             'class' => 'yiicaptchaCaptchaAction',             '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-&gt;field($model, 'verifyCode')-&gt;widget(Captcha::className(), [     'template' =&gt; '<div> <div>{image}</div> <div>{input}</div> </div>',  ]) ?&gt;

 验证码,生成和验证的整个流程就完成了。 

以上是生成验证码的流程,因为验证码数字是在代码中写死的,如果我们需要数字的话,那该怎么办呢?

很好办,我们可以自己写个类来继承CaptchaAction,重写generateVerifyCode方法,例子:

namespace yiicaptcha; class   Newcaptcha extends CaptchaAction {     protected function generateVerifyCode()     {         if ($this-&gt;minLength &gt; $this-&gt;maxLength) {             $this-&gt;maxLength = $this-&gt;minLength;         }         if ($this-&gt;minLength minLength = 3;         }         if ($this-&gt;maxLength &gt; 20) {             $this-&gt;maxLength = 20;         }         $length = mt_rand($this-&gt;minLength, $this-&gt;maxLength);          $letters = '1234567890123456789012';         $vowels = 'aeiou';         $code = '';         for ($i = 0; $i  2 || !($i % 2) &amp;&amp; mt_rand(0, 10) &gt; 9) {                 $code .= $vowels[mt_rand(0, 4)];             } else {                 $code .= $letters[mt_rand(0, 20)];             }         }         return $code;     } }

生成类文件成功。
然后再更改控制器的配置

'captcha' =&gt; [     'class' =&gt; 'yiicaptchaNewcaptcha',     'maxLength' =&gt; 5,     'minLength' =&gt;5 ],

好了,更改完成,让我们来看下效果吧!

yii2验证码样式如何设置

更多yii框架知识,可以观看相关yii教程,!!

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享