【TP5.1】驗證碼校驗 ---驗證器使用
阿新 • • 發佈:2018-11-04
author:kak
wechat:fangkangfk
實現步驟:
在data建立一個Uservaildate的驗證類
寫驗證規則
在登入時對驗證類的呼叫,然後校驗
$userVaildata->check(Request::param())這個方法是獲取使用者輸入的資訊
$userVaildata->getError()這個方法是返回驗證錯誤資訊
首先建立驗證器類
原始碼:
<?php namespace data\validate; use think\Validate; /** * 對使用者輸入登入資料進行驗證 */ class UserValidate extends Validate { /** * 定義驗證規則 * 格式:'欄位名' => ['規則1','規則2'...] * * @var array */ protected $rule = [ 'vertify' => 'require|captcha' ]; /** * 定義錯誤資訊 * 格式:'欄位名.規則名' => '錯誤資訊' * * @var array */ protected $message = [ 'vertify' => [ 'require' => '驗證碼必須有', 'captcha' =>'驗證碼錯誤' ] ]; }
在登入時進行驗證
原始碼:
<?php namespace app\admin\controller; use think\Controller; use data\model\user\User; use data\service\UserService; use Request; use Db,Log; use think\captcha\Captcha; use data\Validate\UserValidate; class Login extends Controller { // 定義邏輯層UserService private $userService; /** * 初始化 */ public function initialize() { $this->userService = new UserService; } /** * 登入 * @return \think\Response */ public function login() { if(Request::isPost()){ $username = Request::param('username'); $password = Request::param('password'); $userVaildata = new UserValidate; // 對驗證類進行驗證 if(!$userVaildata->check(Request::param())){ return json([ 'code' => USER_LOGIN_VALIDATE_ERROR, //$userVaildata->getError()可以獲取到具體的錯誤資訊 'msg' => $userVaildata->getError() ]); } return ajaxRuturn($this->userService->login($username,$password)); } return $this->fetch(); } /** * 驗證碼驗證 */ public function verify() { $config = [ // 驗證碼字型大小 'fontSize' => 30, // 驗證碼位數 'length' => 3, // 關閉驗證碼雜點 'useNoise' => false, ]; $captcha = new Captcha($config); return $captcha->entry(); } }