实现步骤:
在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(); } }