整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

「layui」表单验证:验证注册

「layui」表单验证:验证注册

册界面



手动验证获取短信验证码


代码原文

、知识点

1、JS支持事件处理业务逻辑模型,常用事件

Click 单击

Dblclick 双击

Focus 聚焦

Blur 失去焦点

Mouseover 鼠标悬停

Mousemove 鼠标移动

Mouseout 鼠标移开

Change 改变

Load 页面加载

Keydown 键按下

2、调用

找到对应的标签,加上属性 on事件关键字=”JS代码”。一般调用的JS代码逻辑很复杂,会用函数封装。

3、DOM操作:Document Object Model,文档对象模型。网页文档由一个个的HTML标签组成,操作网页组成元素(标签)。

document.getElementById();

document.getElementsByName();

document.getElementsByTagName();

4、表单提交

方式一:document.getElementById("form1").submit();

方式二:提交按钮类型设置为submit,调用的函数必须要有一个返回值,返回false不提交,true提交;调用函数时前面再加个return 关键字。

5、回车验证的实现。利用用户敲击键盘判断用户按下的是回车键调用检测函数即可。

6、事件参数:event代表对应的标签执行的动作。比如文本框按下键判断是不是回车

Onkeydown=”Test(event);”

<script>

function Test(e){

var e=e||window.event;

if(e.keyCode==13){}

}

</script>

鼠标悬停,显示该位置坐标(相对)

Onmouseover=”alert(event.clientX+”|”+event.clientY);”

二、表单验证

示例源码:

<html>

<head><title>XXX 用户注册</title></head>

<body style="margin-left:auto; margin-right:auto; text-align:center;">

<form name="form1" id="form1" action="register.php" method="post">

<table>

<caption><h3>用户注册</h3></caption>

<tr><th>用户名:</th><td><input onKeyDown="EnterCheck(event);" name="loginid" id="loginid" placeholder="请输入用户名" /></td></tr>

<tr><th>密码:</th><td><input name="pwd" id="pwd" type="password" placeholder="请输入密码" onKeyDown="EnterCheck(event);" /></td></tr>

<tr><th>确认密码:</th><td><input name="repwd" id="repwd" type="password" placeholder="请输入确认密码" onKeyDown="EnterCheck(event);" /></td></tr>

<tr><th>昵称:</th><td><input type="text" name="uname" id="uname" placeholder="请输入昵称" onKeyDown="EnterCheck(event);" /></td></tr>

<tr><th>性别:</th><td><input type="radio" checked id="sex" name="sex" />男<input name="sex" type="radio" id="sex" />女

</td></tr>

<tr><th>喜欢的颜色:</th><td>

<select name="ucolor" id="ucolor">

<option selected value="0">==请选择==</option>

<option value="red">--红色--</option>

<option value="green">--绿色--</option>

<option value="blue">--蓝色--</option>

</select>

</td></tr>

<tr><th>爱好:</th><td><input value="playcomputer" name="cbof[]" id="cbof[]" type="checkbox">玩电脑

<input type="checkbox" value="readingbook" name="cbof[]" id="cbof[]" >看书

<input type="checkbox" value="dosporting" name="cbof[]" id="cbof[]">做运动

</td></tr>

<tr><th>个人简介:</th><td>

<textarea rows="4" name="describe" id="describe" onKeyDown="EnterCheck(event);"></textarea>

</td></tr>

<tr><td></td><td>

<input type="button" value="提交" onClick="return CheckInput();">

<input type="reset" value="重置">

<input type="button" value="取消">

</td></tr>

</table>

</form>

</body>

<script language="javascript" type="text/javascript">

//验证用户输入

function CheckInput(){

var result=false;

//获取用户名文本框对象

var loginid=document.getElementById("loginid");

var pwd=document.getElementById("pwd");

var repwd=document.getElementById("repwd");

var uname=document.getElementById("uname");

var ucolor=document.getElementById("ucolor");

var describe=document.getElementById("describe");

if(CheckIsSafeInputText(loginid,"用户名")){}

else if(CheckIsSafeInputText(pwd,"密码")){}

else if(repwd.value!=pwd.value){

alert("密码与确认密码不一致");

repwd.focus();

}

else if(CheckIsSafeInputText(uname,"昵称")){}

else if(ucolor.value=="0"){

alert("请至少选择一个喜欢的颜色");

ucolor.focus();

}

else if(describe!=null && describe.value.length>256){

alert("个人简介不得超出256个字符");

describe.focus();

}

else

//document.getElementById("form1").submit();

result=true;

return result;

}

//验证文本框是否合法,非法返回true,合法返回false

function CheckIsSafeInputText(obj,msg){

var result=true;

if(obj==null || obj.value=="")

{

alert(msg+"不得为空");//+为字符串连接符

obj.focus();

}

else if(obj.value.length<4 || obj.value.length>16){

alert(msg+"长度在4~16个字符以内");

obj.focus();

}

else

result=false;

return result;

}

//回车验证

function EnterCheck(e){

var e=e || window.event;

if(e.keyCode==13)

CheckInput();

}

</script>

</html>

三、JS外链

JS的代码抽出去作为一个单独的文件,命名要对应,相应的页面通过<script language="javascript" type="text/javascript" src="相对路径"></script>来调用

网页页面的使用中为防止“非人类”的大量操作和防止一些的信息冗余,增加验证码校验是许多网站常用的方式。

而让用户输入字母和数字组合的验证码是最经典也是最常用的方式。
这一篇是纯利用现有JDK提供的绘图类(ImageIO)类制作,这个过程比较复杂且需要了解ImageIO类。

今天发布的第二篇文章是利用Hutool工具类来实现的,该工具类已经封装验证码所需的相关类等,使用起来较为简单和方便。

验证码的生成和校验过程均使用Servlet和JSP的结合来实现,Servlet的相关内容可以参阅

Servlet技术:https://mp.weixin.qq.com/s/__e_ef0SI6kVPiRaU0MXJw

如何利用基础的JSP知识来实现网页的验证码校验呢?

验证码校验分析

首先要验证码的校验的过程。

验证码校验分为三部分:

  1. 生成验证码
  2. 获取用户输入的验证码
  3. 判断验证码是否输入正确

验证码的生成实际就是输出一个图像,所以在这里使用ImageIO来生成图片,然后结合使用随机数(Random)来实现随机生成验证上的内容,最后进而展示出来,然后利用Session对象存储验证码的内容。在用户输入验证码的时候可以用request来获取用户输入的内容,让其余Session对象中保存的验证码内容进行比较,若一致则验证成功,不一致就验证失败。

生成验证码

先创建一个图片的缓冲区:

BufferedImage bi=new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);

创建画布:

Graphics g=bi.getGraphics();

创建颜色:

Color c=new Color(200,150,255);

创建背景颜色:

g.setColor(c);

填充矩形:

g.fillRect(0, 0, 68,22);

将要显示的验证码内容组成元素存入字符串数组:

char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

创建随机的验证码内容:

Random r=new Random();
         int len=ch.length;
         int index; //index用于存放随机数字
         StringBuffer sb=new StringBuffer();
         for(int i=0;i<4;i++)
         {
             index=r.nextInt(len);//产生随机数字
             g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));  //设置颜色
             g.drawString(ch[index]+"",(i*15)+3, 18);//画数字以及数字的位置
             sb.append(ch[index]);
         }

将验证码的内容存入Session及显示在页面上:

 request.getSession().setAttribute("piccode",sb.toString()); 
 ImageIO.write(bi, "JPG", response.getOutputStream()); 

完整代码:

public class ImageServlet  extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedImage bi=new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);//创建图像缓冲区
        Graphics g=bi.getGraphics(); //通过缓冲区创建一个画布
        Color c=new Color(200, 150, 255); //创建颜色
        g.setColor(c);//为画布创建背景颜色
        g.fillRect(0, 0, 68, 22); //填充矩形
        char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//转化为字符型的数组
        Random r=new Random();
        int len=ch.length;
        int index; //index用于存放随机数字
        StringBuffer sb=new StringBuffer();
        for (int i=0; i < 4; i++) {
            index=r.nextInt(len);//产生随机数字
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));  //设置颜色
            g.drawString(ch[index] + "", (i * 15) + 3, 18);//画数字以及数字的位置
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("piccode", sb.toString());
        ImageIO.write(bi, "JPG", response.getOutputStream());
    }
}

测试验证码

在测试之前需要先在web.xml文件中配置一下:

<servlet>
        <servlet-name>ImageServlet</servlet-name>
        <servlet-class>com.kailong.servlet.ImageServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ImageServlet</servlet-name>
        <url-pattern>/imageServlet</url-pattern>
    </servlet-mapping>

启动服务器后在浏览器中输入http://localhost:8080/工程名/imageServlet 即可

验证码的生成已经实现成功,下面实现验证验证码的Servlet。

校验验证码

先新建一个jsp用户界面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录界面</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/loginServlet" method="get" >
    验证码:<input  type="text" name="checkCode"/><br/>
    <img alt="验证码" id="imagecode" src="<%=request.getContextPath()%>/imageServlet"/>
    <input type="submit" value="提交">
</form>
</body>
</html>

校验验证码过程:

  1. 将生成的验证码内容保存在Session对象中
  2. 获取用户输入的验证码内容
  3. 将两个内容进行对照

代码实现:

获取Session中的验证码内容:

String piccode=(String) request.getSession().getAttribute("piccode");

获取用户输入的验证码内容:

String checkCode=request.getParameter("checkCode"); 

验证码判断(使用了PrintWriter将相关内容输出)

response.setContentType("text/html;charset=utf-8");//解决乱码问题
PrintWriter out=response.getWriter();
if(checkCode.equals(piccode))
{
    out.println("验证码输入正确!");
}
else
{
    out.println("验证码输入错误!!!");
}
out.flush();//将流刷新
out.close();//将流关闭

完整代码:

public class LoginServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
    //用于验证验证码
    {
        String piccode=(String) request.getSession().getAttribute("piccode");
        String checkCode=request.getParameter("checkCode");
        response.setContentType("text/html;charset=utf-8");//解决乱码问题
        PrintWriter out=response.getWriter();
        if (checkCode.equals(piccode)) {
            out.println("验证码输入正确!");
        } else {
            out.println("验证码输入错误!!!");
        }
        out.flush();//将流刷新
        out.close();//将流关闭
    }
}

测试验证码校验

测试前先在web.xml文件中配置一下:

 <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.kailong.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>

添加验证码刷新

在验证码生成之后,用户在识别的时候可能不能正确识别,这时候就需要刷新一下重新生成。

添加超链接实现刷新:

login.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录界面</title>
    <script>
        function reloadCode() {
          var time=new Date().getTime();
          document.getElementById("imagecode").src="<%=request.getContextPath()%>/imageGenerate?d="+time;
        }
    </script>
</head>
<body>
<form action="<%=request.getContextPath()%>/loginServlet" method="get" >
    验证码:<input  type="text" name="checkCode"/><br/>
    <img alt="验证码" id="imagecode" src="<%=request.getContextPath()%>/imageServlet"/>
    <a href="javascript:reloadCode();">看不清楚</a><br>
    <br/><input type="submit" value="提交">
</form>
</body>
</html>

js部分的Date相关是防止浏览器缓存后不能正常刷新,添加时间的唯一性来实现能够及时刷新和展示。

js 部分可以参阅:JavaScript 语言入门: https://mp.weixin.qq.com/s/37CaC25_1agb-aXBLhUKtg

也可以在ImageServlet中添加防止浏览器缓存的语句:

response.setHeader("Pragma", "No-cache");

公众号本文地址:https://mp.weixin.qq.com/s/XHucabQ_WwUx2OMDGSTMkw

欢迎关注公众号:愚生浅末。