這篇文章主要介紹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驗證碼樣式的設置方法”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。