zoukankan      html  css  js  c++  java
  • jsp中的javascript的$(document).ready( function() { $("#loginForm").validate()

    转自:https://bbs.csdn.net/topics/392459787?list=71147533

    下面是jsp页面中的JavaScript代码

    $(document).ready(
      function() 
         {
    $("#loginForm").validate(
                                      {
                 rules: {
              validateCode: {remote: "${pageContext.request.contextPath}/servlet/validateCodeServlet"}
                    },
             messages: {
                      username:       {required: "请填写用户名."},
                                                       password:       {required: "请填写密码."},
                       validateCode:   {remote: "验证码不正确.", required: "请填写验证码."}
                 },
             errorLabelContainer: "#messageBox",
             errorPlacement:   function(error, element)
                                                                                  {
                                        error.appendTo($("#loginError").parent());
                                                } 
               }
                                   ); // validate
       } // function
                      );// ready

    请问这个$("#loginForm").validate 的工作原理和过程是什么,它参数中的rules messages 等参数有啥用 ?非常感谢大家。
    以下是validateCodeServlet.java的代码

    /**
     * Copyright &copy; 2015-2020 <a href=" ">JeePlus</a> All rights reserved.
     */
    package com.jeeplus.core.servlet;
     
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Random;
     
    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.apache.commons.lang3.math.NumberUtils;
    import org.apache.commons.lang3.StringUtils;
     
    /**
     * 生成随机验证码
     * @author jeeplus
     * @version 2017-7-27
     */
    @SuppressWarnings("serial")
    public class ValidateCodeServlet extends HttpServlet {
         
        public static final String VALIDATE_CODE = "validateCode";
         
        private int w = 70;
        private int h = 26;
         
        public ValidateCodeServlet() {
            super();
        }
         
        public void destroy() {
            super.destroy(); 
        }
         
        public static boolean validate(HttpServletRequest request, String validateCode){
            String code = (String)request.getSession().getAttribute(VALIDATE_CODE);
            return validateCode.toUpperCase().equals(code); 
        }
     
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String validateCode = request.getParameter(VALIDATE_CODE); // AJAX验证,成功返回true
            if (StringUtils.isNotBlank(validateCode)){
                response.getOutputStream().print(validate(request, validateCode)?"true":"false");
            }else{
                this.doPost(request, response);
            }
        }
     
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            createImage(request,response);
        }
         
        private void createImage(HttpServletRequest request,
                HttpServletResponse response) throws IOException {
             
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
             
            /*
             * 得到参数高,宽,都为数字时,则使用设置高宽,否则使用默认值
             */
            String width = request.getParameter("width");
            String height = request.getParameter("height");
            if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
                w = NumberUtils.toInt(width);
                h = NumberUtils.toInt(height);
            }
             
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
     
            /*
             * 生成背景
             */
            createBackground(g);
     
            /*
             * 生成字符
             */
            String s = createCharacter(g);
            request.getSession().setAttribute(VALIDATE_CODE, s);
     
            g.dispose();
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "JPEG", out);
            out.close();
     
        }
         
        private Color getRandColor(int fc,int bc) { 
            int f = fc;
            int b = bc;
            Random random=new Random();
            if(f>255) {
                f=255; 
            }
            if(b>255) {
                b=255; 
            }
            return new Color(f+random.nextInt(b-f),f+random.nextInt(b-f),f+random.nextInt(b-f)); 
        }
         
        private void createBackground(Graphics g) {
            // 填充背景
            g.setColor(getRandColor(220,250)); 
            g.fillRect(0, 0, w, h);
            // 加入干扰线条
            for (int i = 0; i < 8; i++) {
                g.setColor(getRandColor(40,150));
                Random random = new Random();
                int x = random.nextInt(w);
                int y = random.nextInt(h);
                int x1 = random.nextInt(w);
                int y1 = random.nextInt(h);
                g.drawLine(x, y, x1, y1);
            }
        }
     
        private String createCharacter(Graphics g) {
            char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
                    'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                    'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
            String[] fontTypes = {"Arial","Arial Black","AvantGarde Bk BT","Calibri"}; 
            Random random = new Random();
            StringBuilder s = new StringBuilder();
            for (int i = 0; i < 4; i++) {
                String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
                g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
                g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,26)); 
                g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
    //            g.drawString(r, i*w/4, h-5);
                s.append(r);
            }
            return s.toString();
        }
         
    }

    答案:

    $("#loginForm").validate是validate插件提供的api,是前端做表单验证的;rules是每一项的验证规则; messages 则是验证不通过时的提示信息;remote是指远程验证,插件都有规定的,如果是远程验证,api接口必须返回规定格式的数据,一般是返回boolean值;
    其实就是一个表单拦截功能,在表单数据提交之前先根据提供的规则进行校验,不通过就进行错误提示,通过后才允许提交;         

    追答:

    非常感谢,还要请教一下:
    messages: {
                      username:       {required: "请填写用户名."},
                                                       password:       {required: "请填写密码."},
                       validateCode:   {remote: "验证码不正确.", required: "请填写验证码."}
                 },
    这个错误提示,如果只是没填写密码,这3个提示都显示吗,如果都显示,那肯定不对呀。
       追答
    rules里面的key对应messages里面的key,同时对应form表单里面name为key的选项或者输入框;有些验证插件的机制是遇到一个不通过就会停下,并提示当前的错误信息;有些插件的机制是全部验证完,把所有不通过的错误信息都提示出来;
  • 相关阅读:
    Atitit. visual studio vs2003 vs2005 vs2008  VS2010 vs2012 vs2015新特性 新功能.doc
    Atitit. C#.net clr 2.0  4.0新特性
    Atitit. C#.net clr 2.0  4.0新特性
    Atitit.通过null 参数 反射  动态反推方法调用
    Atitit.通过null 参数 反射  动态反推方法调用
    Atitit..net clr il指令集 以及指令分类  与指令详细说明
    Atitit..net clr il指令集 以及指令分类  与指令详细说明
    Atitit.变量的定义 获取 储存 物理结构 基本类型简化 隐式转换 类型推导 与底层原理 attilaxDSL
    Atitit.变量的定义 获取 储存 物理结构 基本类型简化 隐式转换 类型推导 与底层原理 attilaxDSL
    Atitit.跨语言反射api 兼容性提升与增强 java c#。Net  php  js
  • 原文地址:https://www.cnblogs.com/isme-zjh/p/11820427.html
Copyright © 2011-2022 走看看