网站的后端校验是不可或缺的一部分,我们在后台验证表单时,可能需要把前端传过来的字段一个一个手工校验,或者使用框架的校验去做,今天我编写了一个校验框架,记录如下,
和大家一起分享。《转载请注明出处,谢谢》
1.代码总览
将需要校验的表单信息设置在src目录下的formVerify.xml里;
Xmlparse4FormVerify.java负责读取解析formVerify.xml文件;
VerifyRegularUtil.java负责处理正则表达式相关工作;
2.下面是具体文件及代码
1.formVerify.xml
<?xml version="1.0" encoding="UTF-8"?>
<forms>
<form id="test">
<name>
<text>用户名</text>
<rule>required,min_3,max_20,email</rule>
</name>
<pwd>
<text>密码</text>
<rule>required,min_3,max_20</rule>
</pwd>
<phone>
<text>手机</text>
<rule>phone</rule>
</phone>
<tel>
<text>电话</text>
<rule>tel</rule>
</tel>
<yzbm>
<text>邮编</text>
<rule>yzbm</rule>
</yzbm>
<sfz>
<text>身份证</text>
<rule>sfz</rule>
</sfz>
<url>
<text>url</text>
<rule>url</rule>
</url>
<ip>
<text>ip</text>
<rule>ip</rule>
</ip>
<mac>
<text>mac</text>
<rule>mac</rule>
</mac>
<decimal>
<text>小数点两位</text>
<rule>decimal</rule>
</decimal>
<num>
<text>数字</text>
<rule>num</rule>
</num>
<n>
<text>正整数</text>
<rule>n</rule>
</n>
</form>
<form id="test2">
<name>
<text>用户名</text>
<rule>required,min_3,max_20,email</rule>
</name>
<pwd>
<text>密码</text>
<rule>required,min_3,max_20</rule>
</pwd>
<phone>
<text>手机</text>
<rule>phone</rule>
</phone>
</form>
</forms>
formVerify.xml
<forms>
<form id="test">
<name>
<text>用户名</text>
<rule>required,min_3,max_20,email</rule>
</name>
<pwd>
<text>密码</text>
<rule>required,min_3,max_20</rule>
</pwd>
<phone>
<text>手机</text>
<rule>phone</rule>
</phone>
<tel>
<text>电话</text>
<rule>tel</rule>
</tel>
<yzbm>
<text>邮编</text>
<rule>yzbm</rule>
</yzbm>
<sfz>
<text>身份证</text>
<rule>sfz</rule>
</sfz>
<url>
<text>url</text>
<rule>url</rule>
</url>
<ip>
<text>ip</text>
<rule>ip</rule>
</ip>
<mac>
<text>mac</text>
<rule>mac</rule>
</mac>
<decimal>
<text>小数点两位</text>
<rule>decimal</rule>
</decimal>
<num>
<text>数字</text>
<rule>num</rule>
</num>
<n>
<text>正整数</text>
<rule>n</rule>
</n>
</form>
<form id="test2">
<name>
<text>用户名</text>
<rule>required,min_3,max_20,email</rule>
</name>
<pwd>
<text>密码</text>
<rule>required,min_3,max_20</rule>
</pwd>
<phone>
<text>手机</text>
<rule>phone</rule>
</phone>
</form>
</forms>
formVerify.xml
2.VerifyRegularUtil.java(参考网址:http://www.cnblogs.com/silentjesse/p/3242701.html)
/**
*
*/
package com.linker.util;
import java.util.regex.Pattern;
/**
* Title:VerifyRegularUtil
* description: 验证表单的工具包
* company: linker
* @author zhanjp
* @date 2016年2月22日 上午11:00:52
*/
public class VerifyRegularUtil {
//邮箱
private String email = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
//手机
private String phone = "^[1]+[3,5]+\\d{9}$";
//电话
private String tel = "^(\\d{3,4}-)?\\d{6,8}$";
//邮编
private String yzbm = "^\\d{6}$";
//身份证
private String sfz = "(^\\d{18}$)|(^\\d{15}$)";
//url
private String url = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
//ip
private String ip = "^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";
//物理地址
private String mac = "^[A-F0-9]{2}(-[A-F0-9]{2}){5}$";
//两位小数
private String decimal = "^[0-9]+(.[0-9]{2})?$";
//数字
private String num = "^[0-9]*$";
//正整数
private String n = "^\\+?[1-9][0-9]*$";
/**
* 校验表单
* @param data
* @return
*/
public String verify(String value,String preText,String rule)throws Exception{
String[] rs = rule.split(",");
String errorInfo = null;
for(String s:rs){
if(s.indexOf("|")<0&&s.indexOf("_")<0){
//包含“|”是指或者的关系,比如输入框可以输入邮箱或者手机号,包含“_”,比如min_6指最小6位
switch (s) {
//需要特殊说明文字的在此添加case
case "required":
if(value!=null&&value.trim().length()>0){
}else{
errorInfo = preText + "不能为空";
}
break;
//通用说明走else
default:
errorInfo = verifyByRegular(value,preText,s);
break;
}
if(errorInfo!=null){
//如果已有错误信息,则不需要再次循环
break;
}
}else{
if(s.indexOf("|")>=0){
//包含"或者关系",一般"|"和"_"不会共存,在此不做考虑
if(s.indexOf("_")>=0){
throw new Exception(preText + "规则配置错误");
}
String[] s1 = s.split("|");
for(String s2:s1){
errorInfo = verifyByRegular(preText, value, s2);
if(errorInfo==null){
break;
}
}
}else if(s.indexOf("_")>=0){
String[] s1 = s.split("_");
if(s1[0].equals("min")){
errorInfo = minLen(preText, value, Integer.parseInt(s1[1]));
}else if(s1[0].equals("max")){
errorInfo = maxLen(preText, value, Integer.parseInt(s1[1]));
}else{
throw new Exception("暂不支持这种校验格式:" + s1[0]);
}
}
if(errorInfo!=null){
//如果已有错误信息,则不需要再次循环
break;
}
}
}
return errorInfo;
}
/**
* 根据正则表达式判断是否成立
* @param preText 必传,字段名称
* @param value 必传,字段值
* @param r 必传,校验类型
* @return
*/
private String verifyByRegular(String value,String preText,String r)throws Exception{
String errorInfo = null;
String regex = "";
switch (r) {
case "email":
regex = email;
break;
case "phone":
regex = phone;
break;
case "tel":
regex = tel;
break;
case "yzbm":
regex = yzbm;
break;
case "sfz":
regex = sfz;
break;
case "n":
regex = n;
break;
case "url":
regex = url;
break;
case "ip":
regex = ip;
break;
case "mac":
regex = mac;
break;
case "decimal":
regex = decimal;
break;
case "num":
regex = num;
default:
break;
}
if(regex.equals("")){
throw new Exception("暂不支持这种校验格式:" + r);
}else{
boolean flg = Pattern.matches(regex, value);
if(flg){
}else{
errorInfo = preText + "格式不正确,请重新检查!";
}
}
return errorInfo;
}
/**
* 校验最少长度
* @param preText
* @param value
* @param min
* @return
*/
private String minLen(String preText,String value,int min){
String errorInfo = null;
if(value!=null&&value.trim().length()>=min){
}else{
errorInfo = preText + "最少长度为" + min +"位。";
}
return errorInfo;
}
private String maxLen(String preText,String value,int max){
String errorInfo = null;
if(value!=null&&value.trim().length()<=max){
}else{
errorInfo = preText + "最大长度为" + max +"位。";
}
return errorInfo;
}
}
VerifyRegularUtil.java
*
*/
package com.linker.util;
import java.util.regex.Pattern;
/**
* Title:VerifyRegularUtil
* description: 验证表单的工具包
* company: linker
* @author zhanjp
* @date 2016年2月22日 上午11:00:52
*/
public class VerifyRegularUtil {
//邮箱
private String email = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
//手机
private String phone = "^[1]+[3,5]+\\d{9}$";
//电话
private String tel = "^(\\d{3,4}-)?\\d{6,8}$";
//邮编
private String yzbm = "^\\d{6}$";
//身份证
private String sfz = "(^\\d{18}$)|(^\\d{15}$)";
//url
private String url = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
//ip
private String ip = "^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";
//物理地址
private String mac = "^[A-F0-9]{2}(-[A-F0-9]{2}){5}$";
//两位小数
private String decimal = "^[0-9]+(.[0-9]{2})?$";
//数字
private String num = "^[0-9]*$";
//正整数
private String n = "^\\+?[1-9][0-9]*$";
/**
* 校验表单
* @param data
* @return
*/
public String verify(String value,String preText,String rule)throws Exception{
String[] rs = rule.split(",");
String errorInfo = null;
for(String s:rs){
if(s.indexOf("|")<0&&s.indexOf("_")<0){
//包含“|”是指或者的关系,比如输入框可以输入邮箱或者手机号,包含“_”,比如min_6指最小6位
switch (s) {
//需要特殊说明文字的在此添加case
case "required":
if(value!=null&&value.trim().length()>0){
}else{
errorInfo = preText + "不能为空";
}
break;
//通用说明走else
default:
errorInfo = verifyByRegular(value,preText,s);
break;
}
if(errorInfo!=null){
//如果已有错误信息,则不需要再次循环
break;
}
}else{
if(s.indexOf("|")>=0){
//包含"或者关系",一般"|"和"_"不会共存,在此不做考虑
if(s.indexOf("_")>=0){
throw new Exception(preText + "规则配置错误");
}
String[] s1 = s.split("|");
for(String s2:s1){
errorInfo = verifyByRegular(preText, value, s2);
if(errorInfo==null){
break;
}
}
}else if(s.indexOf("_")>=0){
String[] s1 = s.split("_");
if(s1[0].equals("min")){
errorInfo = minLen(preText, value, Integer.parseInt(s1[1]));
}else if(s1[0].equals("max")){
errorInfo = maxLen(preText, value, Integer.parseInt(s1[1]));
}else{
throw new Exception("暂不支持这种校验格式:" + s1[0]);
}
}
if(errorInfo!=null){
//如果已有错误信息,则不需要再次循环
break;
}
}
}
return errorInfo;
}
/**
* 根据正则表达式判断是否成立
* @param preText 必传,字段名称
* @param value 必传,字段值
* @param r 必传,校验类型
* @return
*/
private String verifyByRegular(String value,String preText,String r)throws Exception{
String errorInfo = null;
String regex = "";
switch (r) {
case "email":
regex = email;
break;
case "phone":
regex = phone;
break;
case "tel":
regex = tel;
break;
case "yzbm":
regex = yzbm;
break;
case "sfz":
regex = sfz;
break;
case "n":
regex = n;
break;
case "url":
regex = url;
break;
case "ip":
regex = ip;
break;
case "mac":
regex = mac;
break;
case "decimal":
regex = decimal;
break;
case "num":
regex = num;
default:
break;
}
if(regex.equals("")){
throw new Exception("暂不支持这种校验格式:" + r);
}else{
boolean flg = Pattern.matches(regex, value);
if(flg){
}else{
errorInfo = preText + "格式不正确,请重新检查!";
}
}
return errorInfo;
}
/**
* 校验最少长度
* @param preText
* @param value
* @param min
* @return
*/
private String minLen(String preText,String value,int min){
String errorInfo = null;
if(value!=null&&value.trim().length()>=min){
}else{
errorInfo = preText + "最少长度为" + min +"位。";
}
return errorInfo;
}
private String maxLen(String preText,String value,int max){
String errorInfo = null;
if(value!=null&&value.trim().length()<=max){
}else{
errorInfo = preText + "最大长度为" + max +"位。";
}
return errorInfo;
}
}
VerifyRegularUtil.java
3.Xmlparse4FormVerify.java
/**
*
*/
package com.linker.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Title:Xmlparse4FormVerify
* description: 读取xml中配置的表单验证信息
* company: linker
* @author zhanjp
* @date 2016年2月22日 上午9:33:59
*/
public class Xmlparse4FormVerify {
private static DocumentBuilder db = null;
private static DocumentBuilderFactory dbf = null;
private static Document dt = null;
public static Xmlparse4FormVerify xp;
/**
* 初始化DocumentBuilder等信息
* @return
*/
public Xmlparse4FormVerify getInstance(){
if(xp==null){
xp = new Xmlparse4FormVerify();
}
return xp;
}
static{
try {
//返回documentBuilderFactory
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
String basePath = new Xmlparse4FormVerify().getClass().getClassLoader().getResource("/").getPath();
File f = new File(basePath + "formVerify.xml");
//获取xml文件的dom对象
dt = db.parse(f);
} catch (ParserConfigurationException e) {
e.printStackTrace();
System.out.println("class:Xmlparse4FormVerify>>documentBuilder对象初始化失败。");
} catch (SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("class:Xmlparse4FormVerify>>解析formVerify.xml文档失败");
}
}
/**
* 根据表单ID和表单参数进行校验
* @param formId 表单ID
* @param pMap 表单参数
* @return flag-0:成功,1:失败; msg-消息
* @throws Exception
*/
public static String verifyForm(String formId,Map<String, String> pMap)throws Exception{
if(dt==null){
throw new Exception("未能正确初始化。");
}
String errorInfo = null;
//开始解析xml文档
//获取xml文件跟节点
Element element = dt.getDocumentElement();
//获取根节点下的子节点列表
NodeList cList = element.getChildNodes();
List<Node> forms = new ArrayList<>();
for (int i = 0; i < cList.getLength(); i++) {
Node tNode = cList.item(i);
if(tNode.getNodeName().equals("form")){
forms.add(tNode);
}
}
for (int i = 0; i < forms.size(); i++) {
Node node1 = forms.get(i);
String nodeId = node1.getAttributes().getNamedItem("id").getNodeValue();
// System.out.println("节点id:" + nodeId+","+"节点name"+node1.getNodeName());
if(nodeId.equals(formId)){
NodeList cList2 = node1.getChildNodes();
//开始校验
Set<String> keys = pMap.keySet();
Iterator<String> iter = keys.iterator();
while (iter.hasNext()) {
String key = iter.next();
for (int j = 0; j < cList2.getLength(); j++) {
Node node = cList2.item(j);
// System.out.println("clist2,node:"+node.getNodeName());
if(node.getNodeName().equals(key)){
String value = pMap.get(key);
String preText = "";
String rule = "";
NodeList cList3 = node.getChildNodes();
for(int m = 0;m < cList3.getLength(); m++){
if(cList3.item(m).getNodeName()=="text"){
preText = cList3.item(m).getTextContent();
}else if(cList3.item(m).getNodeName()=="rule"){
rule = cList3.item(m).getTextContent();
}
}
//TODO 校验
errorInfo = new VerifyRegularUtil().verify(value, preText, rule);
if(errorInfo!=null){
return errorInfo;
}
}
}
}
break;
}
}
return errorInfo;
}
}
Xmlparse4FormVerify.java
*
*/
package com.linker.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Title:Xmlparse4FormVerify
* description: 读取xml中配置的表单验证信息
* company: linker
* @author zhanjp
* @date 2016年2月22日 上午9:33:59
*/
public class Xmlparse4FormVerify {
private static DocumentBuilder db = null;
private static DocumentBuilderFactory dbf = null;
private static Document dt = null;
public static Xmlparse4FormVerify xp;
/**
* 初始化DocumentBuilder等信息
* @return
*/
public Xmlparse4FormVerify getInstance(){
if(xp==null){
xp = new Xmlparse4FormVerify();
}
return xp;
}
static{
try {
//返回documentBuilderFactory
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
String basePath = new Xmlparse4FormVerify().getClass().getClassLoader().getResource("/").getPath();
File f = new File(basePath + "formVerify.xml");
//获取xml文件的dom对象
dt = db.parse(f);
} catch (ParserConfigurationException e) {
e.printStackTrace();
System.out.println("class:Xmlparse4FormVerify>>documentBuilder对象初始化失败。");
} catch (SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("class:Xmlparse4FormVerify>>解析formVerify.xml文档失败");
}
}
/**
* 根据表单ID和表单参数进行校验
* @param formId 表单ID
* @param pMap 表单参数
* @return flag-0:成功,1:失败; msg-消息
* @throws Exception
*/
public static String verifyForm(String formId,Map<String, String> pMap)throws Exception{
if(dt==null){
throw new Exception("未能正确初始化。");
}
String errorInfo = null;
//开始解析xml文档
//获取xml文件跟节点
Element element = dt.getDocumentElement();
//获取根节点下的子节点列表
NodeList cList = element.getChildNodes();
List<Node> forms = new ArrayList<>();
for (int i = 0; i < cList.getLength(); i++) {
Node tNode = cList.item(i);
if(tNode.getNodeName().equals("form")){
forms.add(tNode);
}
}
for (int i = 0; i < forms.size(); i++) {
Node node1 = forms.get(i);
String nodeId = node1.getAttributes().getNamedItem("id").getNodeValue();
// System.out.println("节点id:" + nodeId+","+"节点name"+node1.getNodeName());
if(nodeId.equals(formId)){
NodeList cList2 = node1.getChildNodes();
//开始校验
Set<String> keys = pMap.keySet();
Iterator<String> iter = keys.iterator();
while (iter.hasNext()) {
String key = iter.next();
for (int j = 0; j < cList2.getLength(); j++) {
Node node = cList2.item(j);
// System.out.println("clist2,node:"+node.getNodeName());
if(node.getNodeName().equals(key)){
String value = pMap.get(key);
String preText = "";
String rule = "";
NodeList cList3 = node.getChildNodes();
for(int m = 0;m < cList3.getLength(); m++){
if(cList3.item(m).getNodeName()=="text"){
preText = cList3.item(m).getTextContent();
}else if(cList3.item(m).getNodeName()=="rule"){
rule = cList3.item(m).getTextContent();
}
}
//TODO 校验
errorInfo = new VerifyRegularUtil().verify(value, preText, rule);
if(errorInfo!=null){
return errorInfo;
}
}
}
}
break;
}
}
return errorInfo;
}
}
Xmlparse4FormVerify.java
4.测试代码:(本项目控制层SpringMvc,可根据自己情况适当更改)
@RequestMapping(value="/test2017")
public void test2(){
HashMap<String, String> pMap = new HashMap<>();
pMap.put("name", "944593237@qq.com");
pMap.put("pwd", "123456");
pMap.put("phone", "15138456324");
pMap.put("tel", "123456");
pMap.put("yzbm", "3100562");
pMap.put("sfz", "413025199802243366");
pMap.put("url", "http://www.baidu.com");
pMap.put("ip", "172.1.4.113");
pMap.put("mac", "EC-B1-D7-49-20-33");
pMap.put("decimal", "123456.22");
pMap.put("num", "123");
pMap.put("n", "2");
try {
String errorInfo = Xmlparse4FormVerify.verifyForm("test2", pMap);
if(errorInfo!=null){
System.out.println(errorInfo);
}else{
System.out.println("表单验证通过!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
测试
public void test2(){
HashMap<String, String> pMap = new HashMap<>();
pMap.put("name", "944593237@qq.com");
pMap.put("pwd", "123456");
pMap.put("phone", "15138456324");
pMap.put("tel", "123456");
pMap.put("yzbm", "3100562");
pMap.put("sfz", "413025199802243366");
pMap.put("url", "http://www.baidu.com");
pMap.put("ip", "172.1.4.113");
pMap.put("mac", "EC-B1-D7-49-20-33");
pMap.put("decimal", "123456.22");
pMap.put("num", "123");
pMap.put("n", "2");
try {
String errorInfo = Xmlparse4FormVerify.verifyForm("test2", pMap);
if(errorInfo!=null){
System.out.println(errorInfo);
}else{
System.out.println("表单验证通过!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
测试