validatoin 下载
官网:
下载:
基本的环境搭建
<%@ page contentType="text/html;charset=UTF-8" language="java" %><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%>demo 01
常见验证配置
- 源码237行有默认配置
- 源码 326有验证失败的错误消息,也可以知道默认提供的验证
- 默认的错误消息显示在
<%@ page contentType="text/html;charset=UTF-8" language="java" %><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%>demo 01
远程验证
前台代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%>demo 01
后台代码
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")@Controllerpublic class RegisterController { private static final Gson gson = new Gson(); @RequestMapping(value = "check",method = RequestMethod.POST) public ResponseEntitycheckEmail( @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"); } }}
需要注意:
-
添加
onkeyup : false
属性,因为默认在验证失败之后,再次输入的话,每每按下键盘都会向后台发起ajax请求 -
只需要添加验证的url即可,因为会自动添加input的值
-
需要添加
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 + "/";%>demo 01
/** * 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 + "/";%>demo 01
美化错误消息
<%@ page contentType="text/html;charset=UTF-8" language="java" %><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%>demo 01