新聞中心
這篇文章主要介紹yii2驗證碼樣式的設置方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
成都地區(qū)優(yōu)秀IDC服務器托管提供商(創(chuàng)新互聯(lián)建站).為客戶提供專業(yè)的成都服務器托管,四川各地服務器托管,成都服務器托管、多線服務器托管.托管咨詢專線:18982081108
yii2驗證碼樣式如何設置
第一步,控制器:
在任意controller里面重寫方法
public function actions() { return [ 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, 'backColor' => 0x000000,//背景顏色 'maxLength' => 6, //最大顯示個數(shù) 'minLength' => 5,//最少顯示個數(shù) 'padding' => 5,//間距 'height' => 40,//高度 'width' => 130, //寬度 'foreColor' => 0xffffff, //字體顏色 'offset' => 4, //設置字符偏移量 有效果 ], ]; }
第二步,表單模型:
這里只給出驗證碼相關(guān)的部分。
相關(guān)文章教程推薦:yii教程
class ContactForm extends Model{ public $verifyCode; public function rules(){ return [ ['verifyCode', 'required'], ['verifyCode', 'captcha'], ]; } }
驗證規(guī)則里面驗證碼的驗證器是captcha
。
第三步,視圖:
用ActiveForm生成對應字段。
captchaAction
參數(shù)指定第一步是在寫在哪里的,默認是site
里面。
= $form->field($model, 'verifyCode')->widget(Captcha::className(), [ 'template' => '', ]) ?>{image}{input}
驗證碼,生成和驗證的整個流程就完成了。
以上是生成驗證碼的流程,因為驗證碼數(shù)字是在代碼中寫死的,如果我們需要數(shù)字的話,那該怎么辦呢?
很好辦,我們可以自己寫個類來繼承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驗證碼樣式的設置方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
標題名稱:yii2驗證碼樣式的設置方法
本文地址:http://www.dlmjj.cn/article/jcgssj.html