第一步按常规的登录写好H5网页,再再控制器里面写好方法,注意还要在controller文件夹同意目录下新建一个validate层,在里面新建一个验证器,写你要验证的规则。下面来看看代码:
1、H5,我这个是用的异步提交表单的,下面有ajax
<form method="post" class="layui-form" οnsubmit="return to_login()"> <input type="text" name="admin_name" id="name" placeholder="请输入用户名" class="layui-input"/> <hr class="hr15"> <input type="password" name="password" id="password" placeholder="请输入密码" class="layui-input"/> <hr class="hr15"> <input style="width:120px;float:left" type="text" id="captcha" placeholder="请输入验证码" name="captcha" class="layui-input"/> <img id="captcha" style="width:150px;height:50px;display: inline-block;float:right;" src="{:captcha_src()}" alt="captcha" οnclick="this.src='{:captcha_src()}'"/> <hr class="hr15"> <input class="loginin" value="登录" type="submit" lay-submit lay-filter="login" style="width:100%;" > <hr class="hr20" > <div> </div> </form>
2、ajax:
function to_login() { $.ajax({ type: 'POST', url: '/index/控制器名称/方法', dataType: 'json', data: $("form").serialize(),//获取表单内容 success: function (e) { console.log(e); layer.msg(e.error_msg); if (e == 'jr') { layer.msg('请求成功'); window.location.href = "/index/index/main"; } else { layer.msg(e); $("#captcha").click(); //验证码输入错误的时候点击刷新 } } }); return false; }
3、控制器
$validate = new Logincode();//调用验证器 $data = ['username' => $username, 'password' => $password, 'captcha' => $captcha]; //验证是否符合验证器里定义(验证码)的规范,不符合返回错误信息 if (!$validate->check($data)) { return json($validate->getError()); }
4、验证器
// 验证规则 protected $rule = [ 'captcha' => 'require|checkCaptcha:null', ]; protected $message = [ 'captcha.require' => '验证码错误1!', //验证码空的时候验证的它 ]; protected function checkCaptcha($value) //验证码输入的进验证的它 { $captcha = new Captcha(); if ($captcha->check($value)) { return true; } else { return '验证码错误2!'; } }
5、验证码图片设置,打开application文件夹下的config.php找到如下代码配置你想要的验证码类型
'captcha' => [ // 验证码字符集合 'codeSet' => '1234567890',/*abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY*/ // 验证码字体大小(px) 'fontSize' => 25, // 是否画混淆曲线 'useCurve' => false, // 验证码图片高度 'imageH' => 50, // 验证码图片宽度 'imageW' => 200, // 验证码位数 'length' => 4 , // 验证成功后是否重置 'reset' => true ],