121 项目 031 笔记向 jquery validation

原创
2017/03/19 05:51
阅读数 100

validatoin 下载

官网:https://jqueryvalidation.org/

下载:https://github.com/jquery-validation/jquery-validation/releases

基本的环境搭建

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>demo 01</title>
</head>
<body>

<form action="#" id="fone">
    <input type="submit" value="提交"/>
</form>

<script type="text/javascript" src="<%=path%>/assets/jq/jquery.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/jquery.validate.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#fone').validate({
            // 设置为debug模式,则不会提交
            debug : true
        });
    });

</script>
</body>
</html>

常见验证配置

  1. 源码237行有默认配置
  2. 源码 326有验证失败的错误消息,也可以知道默认提供的验证
  3. 默认的错误消息显示在
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>demo 01</title>
    <link rel="stylesheet" type="text/css" href="<%=path %>/assets/css/reset.css" />
    <style>
        .form-label{
            display: block;
        }

        .tip-span{
            width: 80px;
            height: 25px;
            display: inline-block;
            line-height: 25px;
            text-align: right;
        }


    </style>
</head>
<body>

<form action="#" id="fone">
    <label for="fone" class="form-label">
        <div class="tip-span">用户名:</div>
        <input type="text" name="name"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">email:</div>
        <input type="text" name="email"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">年龄:</div>
        <input type="text" name="age"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">密码:</div>
        <input id="password" type="password" name="password"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">确认密码:</div>
        <input id="confirm-pass" type="password" name="confirm"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">地址:</div>
        <select name="address">
            <option value="">---请选择---</option>
            <option value="beijing">北京</option>
            <option value="shanghai">上海</option>
            <option value="nanjing">南京</option>
            <option value="hangzhou">杭州</option>
        </select>
    </label>
    <label for="fone">
        <div class="tip-span">爱好:</div>
        看书:<input type="checkbox" name="like" value="看书"/>
        音乐:<input type="checkbox" name="like" value="音乐"/>
        电影:<input type="checkbox" name="like" value="电影"/>
    </label>
    <label for="fone" class="form-label">
        <input type="submit" value="提交"/>
    </label>

</form>

<script type="text/javascript" src="<%=path%>/assets/jq/jquery.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/jquery.validate.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#fone').validate({
            // 设置为debug模式,则不会提交
            debug : true,
            // 配置具体的验证规则,validation 可憎通过name来选择dom对象
            rules : {
                //
                name : {
                    // 如果有参数,则写参数,没有则写true,多个参数,则用数组
                    required : true
                },
                email : {
                    email : true
                },
                age : {
                    required : true,
                    number : true,
                    min : 18,
                    max : 100
                },
                password : {
                    required : true,
                    rangelength : [6,20]
                },
                // 此处输入的是密码框的ID
                confirm : {
                    equalTo : '#password'
                },
                address : {
                    required : true
                },
                like : {
                    required : true
                }
            }
        });
    });

</script>
</body>
</html>

远程验证

前台代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>demo 01</title>
    <link rel="stylesheet" type="text/css" href="<%=path %>/assets/css/reset.css" />
    <style>
        .form-label{
            display: block;
        }

        .tip-span{
            width: 80px;
            height: 25px;
            display: inline-block;
            line-height: 25px;
            text-align: right;
        }


    </style>
</head>
<body>

<form action="#" id="fone">
    <label for="fone" class="form-label">
        <div class="tip-span">email:</div>
        <input type="text" name="email"/>
    </label>
    <label for="fone" class="form-label">
        <input type="submit" value="提交"/>
    </label>

</form>

<script type="text/javascript" src="<%=path%>/assets/jq/jquery.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/jquery.validate.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#fone').validate({
            // 设置为debug模式,则不会提交
            debug : true,
            // 如果验证失败,则每次按键都会有ajax请求,默认为true
            onkeyup : false,
            // 配置具体的验证规则,validation 可憎通过name来选择dom对象
            rules : {
                email : {
                    email : true,
                    // 只需要添加验证的url,且默认为GET请求
                    remote : {
                        url : '<%=path%>/register/check',
                        type : 'POST'
                    }

                }
            }
        });
    });

</script>
</body>
</html>

后台代码

package com.laolang.jq.validation.web;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RequestMapping("register")
@Controller
public class RegisterController {

    private static final Gson gson = new Gson();

    @RequestMapping(value = "check",method = RequestMethod.POST)
    public ResponseEntity<String> checkEmail( @RequestParam(value = "email",required = false) String email){
        if(StringUtils.equals(email,"xiaodaima2016@163.com") || StringUtils.equals(email,"laolang2016@163.com")){
            return ResponseEntity.ok("true");
        }else{
            return ResponseEntity.ok("false");
        }
    }
}

需要注意:

  1. 添加 onkeyup : false属性,因为默认在验证失败之后,再次输入的话,每每按下键盘都会向后台发起ajax请求

  2. 只需要添加验证的url即可,因为会自动添加input的值

  3. 需要添加type:POST,因为默认请求方式为GET

自定义验证方法

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>demo 01</title>
    <link rel="stylesheet" type="text/css" href="<%=path %>/assets/css/reset.css" />
    <style>
        .form-label{
            display: block;
        }

        .tip-span{
            width: 80px;
            height: 25px;
            display: inline-block;
            line-height: 25px;
            text-align: right;
        }


    </style>
</head>
<body>

<form action="#" id="fone">
    <label for="fone" class="form-label">
        <div class="tip-span">头像:</div>
        <input type="file" name="pic"/>
    </label>
    <label for="fone" class="form-label">
        <input type="submit" value="提交"/>
    </label>

</form>

<script type="text/javascript" src="<%=path%>/assets/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/jquery.validate.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/validation-config.js"></script>
<script type="text/javascript">



    $(function () {
        $('#fone').validate({
            // 设置为debug模式,则不会提交
            debug : true,
            // 如果验证失败,则每次按键都会有ajax请求,默认为true
            onkeyup : false,
            // 配置具体的验证规则,validation 可憎通过name来选择dom对象
            rules : {
                pic : {
                    required : true,
                    // 调用自定义的验证方法
                    fileExt : "jpg|gif|png"
                }
            }
        });
    });

</script>
</body>
</html>
/**
 * Created by laolang2016 on 2017/3/19 0019.
 */


/**
 * fileExt为自定义的验证规则名称
 * func 为验证函数
 * $.validator.format可以格式化输出
 */
$.validator.addMethod("fileExt",
    /**
     * 验证函数
     * @param value 表单值
     * @param element dom元素
     * @param params
     * @returns {boolean}
     */
    function (value, element, params) {
        var reg = new RegExp("\.(" + params + ")$", "i");
        return reg.test(value);
    },
    $.validator.format('文件类型必须为:{0}格式')
);

本地化错误消息

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>demo 01</title>
    <link rel="stylesheet" type="text/css" href="<%=path %>/assets/css/reset.css" />
    <style>
        .form-label{
            display: block;
        }

        .tip-span{
            width: 80px;
            height: 25px;
            display: inline-block;
            line-height: 25px;
            text-align: right;
        }


    </style>
</head>
<body>

<form action="#" id="fone">
    <label for="fone" class="form-label">
        <div class="tip-span">用户名:</div>
        <input type="text" name="name"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">email:</div>
        <input type="text" name="email"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">年龄:</div>
        <input type="text" name="age"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">密码:</div>
        <input id="password" type="password" name="password"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">确认密码:</div>
        <input id="confirm-pass" type="password" name="confirm"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">头像:</div>
        <input type="file" name="pic"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">地址:</div>
        <select name="address">
            <option value="">---请选择---</option>
            <option value="beijing">北京</option>
            <option value="shanghai">上海</option>
            <option value="nanjing">南京</option>
            <option value="hangzhou">杭州</option>
        </select>
    </label>
    <label for="fone">
        <div class="tip-span">爱好:</div>
        看书:<input type="checkbox" name="like" value="看书"/>
        音乐:<input type="checkbox" name="like" value="音乐"/>
        电影:<input type="checkbox" name="like" value="电影"/>
    </label>
    <label for="fone" class="form-label">
        <input type="submit" value="提交"/>
    </label>

</form>

<script type="text/javascript" src="<%=path%>/assets/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/jquery.validate.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/validation-config.js"></script>
<script type="text/javascript">



    $(function () {
        $('#fone').validate({
            // 设置为debug模式,则不会提交
            debug : true,
            // 如果验证失败,则每次按键都会有ajax请求,默认为true
            onkeyup : false,
            // 配置具体的验证规则,validation 可憎通过name来选择dom对象
            rules : {
                //
                name : {
                    // 如果有参数,则写参数,没有则写true,多个参数,则用数组
                    required : true
                },
                email : {
                    email : true,
                    // 只需要添加验证的url,且默认为GET请求
                    remote : {
                        url : '<%=path%>/register/check',
                        type : 'POST'
                    }

                },
                age : {
                    required : true,
                    number : true,
                    min : 18,
                    max : 100
                },
                password : {
                    required : true,
                    rangelength : [6,20]
                },
                // 此处输入的是密码框的ID
                confirm : {
                    equalTo : '#password'
                },
                address : {
                    required : true
                },
                like : {
                    required : true
                },
                pic : {
                    // 调用自定义的验证方法
                    fileExt : "jpg|gif|png"
                }
            },
            messages : {
                name : {
                    required : '请填写用户名'
                },
                email : {
                    email : '邮箱格式不正确',
                    remote : '该邮箱已注册'
                },
                age : {
                    required : '请赶写年龄',
                    number : '必须填写数字',
                    min : '最小年龄为18周岁',
                    max : '最大年龄为100周岁'
                },
                password : {
                    required : '请输入密码',
                    rangelength : $.validator.format('密码长度在{0}-{1}之间')
                },
                confirm : {
                    equalTo : '两次输入密码不一致'
                },
                address : {
                    required : '请选择地址'
                },
                like : {
                    required : '请选择爱好'
                },
                pic : {
                    fileExt : $.validator.format("头像图片格式为:{0}")
                }
            }
        });
    });

</script>
</body>
</html>

美化错误消息

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>demo 01</title>
    <link rel="stylesheet" type="text/css" href="<%=path %>/assets/css/reset.css" />
    <style>
        .form-label{
            display: block;
        }

        .tip-span{
            width: 80px;
            height: 25px;
            display: inline-block;
            line-height: 25px;
            text-align: right;
        }

        form span{
            color: red;
            background-image: url("assets/image/error.png");
            background-repeat: no-repeat;
            padding-left: 18px;
        }

        .ok{
            background-image: url("assets/image/right.png");
            background-repeat: no-repeat;
            padding-left: 18px;
        }


    </style>
</head>
<body>

<form action="#" id="fone">
    <label for="fone" class="form-label">
        <div class="tip-span">用户名:</div>
        <input type="text" name="name"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">email:</div>
        <input type="text" name="email"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">年龄:</div>
        <input type="text" name="age"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">密码:</div>
        <input id="password" type="password" name="password"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">确认密码:</div>
        <input id="confirm-pass" type="password" name="confirm"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">头像:</div>
        <input type="file" name="pic"/>
    </label>
    <label for="fone" class="form-label">
        <div class="tip-span">地址:</div>
        <select name="address">
            <option value="">---请选择---</option>
            <option value="beijing">北京</option>
            <option value="shanghai">上海</option>
            <option value="nanjing">南京</option>
            <option value="hangzhou">杭州</option>
        </select>
    </label>
    <label for="fone">
        <div class="tip-span">爱好:</div>
        看书:<input type="checkbox" name="like" value="看书"/>
        音乐:<input type="checkbox" name="like" value="音乐"/>
        电影:<input type="checkbox" name="like" value="电影"/>
    </label>
    <label for="fone" class="form-label">
        <input type="submit" value="提交"/>
    </label>

</form>

<script type="text/javascript" src="<%=path%>/assets/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/jquery.validate.min.js"></script>
<script type="text/javascript" src="<%=path%>/assets/validation/validation-config.js"></script>
<script type="text/javascript">



    $(function () {
        $('#fone').validate({
            // 设置为debug模式,则不会提交
            debug : true,
            // 如果验证失败,则每次按键都会有ajax请求,默认为true
            onkeyup : false,
            // 保存错误消息的标签
            errorElement : 'span',
            errorPlacement : function (span,element) {
                $(element).siblings("span").remove();
                $(element).parent().append(span);
            },
            // 如果是字符串,则此样式加到errorElment指定的标签中
            //success:"ok",
            success:function(span){
                $(span).attr("class","ok");
            },
            errorClass : 'error-class',
            // 配置具体的验证规则,validation 可憎通过name来选择dom对象
            rules : {
                //
                name : {
                    // 如果有参数,则写参数,没有则写true,多个参数,则用数组
                    required : true
                },
                email : {
                    required : true,
                    email : true,
                    // 只需要添加验证的url,且默认为GET请求
                    remote : {
                        url : '<%=path%>/register/check',
                        type : 'POST'
                    }

                },
                age : {
                    required : true,
                    number : true,
                    min : 18,
                    max : 100
                },
                password : {
                    required : true,
                    rangelength : [6,20]
                },
                // 此处输入的是密码框的ID
                confirm : {
                    required : true,
                    equalTo : '#password'
                },
                address : {
                    required : true
                },
                like : {
                    required : true
                },
                pic : {
                    // 调用自定义的验证方法
                    fileExt : "jpg|gif|png"
                }
            },
            messages : {
                name : {
                    required : '请填写用户名'
                },
                email : {
                    required : '请输入邮箱地址',
                    email : '邮箱格式不正确',
                    remote : '该邮箱已注册'
                },
                age : {
                    required : '请赶写年龄',
                    number : '必须填写数字',
                    min : '最小年龄为18周岁',
                    max : '最大年龄为100周岁'
                },
                password : {
                    required : '请输入密码',
                    rangelength : $.validator.format('密码长度在{0}-{1}之间')
                },
                confirm : {
                    required : '请输入确认密码',
                    equalTo : '两次输入密码不一致'
                },
                address : {
                    required : '请选择地址'
                },
                like : {
                    required : '请选择爱好'
                },
                pic : {
                    fileExt : $.validator.format("头像图片格式为:{0}")
                }
            }
        });
    });

</script>
</body>
</html>

输入图片说明

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部
返回顶部
顶部