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->field($model,?'verifyCode')->widget(Captcha::className(),?[ ????'template'?=>?'<div> <div>{image}</div> <div>{input}</div> </div>', ?])??>
?驗證碼,生成和驗證的整個流程就完成了。?
以上是生成驗證碼的流程,因為驗證碼數字是在代碼中寫死的,如果我們需要數字的話,那該怎么辦呢?
很好辦,我們可以自己寫個類來繼承CaptchaAction,重寫generateVerifyCode方法,例子:
namespace?yiicaptcha; class???Newcaptcha?extends?CaptchaAction { ????protected?function?generateVerifyCode() ????{ ????????if?($this->minLength?>?$this->maxLength)?{ ????????????$this->maxLength?=?$this->minLength; ????????} ????????if?($this->minLength?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??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'?=>?'yiicaptchaNewcaptcha', ????'maxLength'?=>?5, ????'minLength'?=>5 ],
好了,更改完成,讓我們來看下效果吧!
更多yii框架知識,可以觀看相關yii教程,!!
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END