網站的后端校驗是不可或缺的一部分,我們在后台驗證表單時,可能需要把前端傳過來的字段一個一個手工校驗,或者使用框架的校驗去做,今天我編寫了一個校驗框架,記錄如下,
和大家一起分享。《轉載請注明出處,謝謝》
1.代碼總覽
將需要校驗的表單信息設置在src目錄下的formVerify.xml里;
Xmlparse4FormVerify.java負責讀取解析formVerify.xml文件;
VerifyRegularUtil.java負責處理正則表達式相關工作;
2.下面是具體文件及代碼
1.formVerify.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <forms> 3 <form id="test"> 4 <name> 5 <text>用戶名</text> 6 <rule>required,min_3,max_20,email</rule> 7 </name> 8 <pwd> 9 <text>密碼</text> 10 <rule>required,min_3,max_20</rule> 11 </pwd> 12 <phone> 13 <text>手機</text> 14 <rule>phone</rule> 15 </phone> 16 <tel> 17 <text>電話</text> 18 <rule>tel</rule> 19 </tel> 20 <yzbm> 21 <text>郵編</text> 22 <rule>yzbm</rule> 23 </yzbm> 24 <sfz> 25 <text>身份證</text> 26 <rule>sfz</rule> 27 </sfz> 28 <url> 29 <text>url</text> 30 <rule>url</rule> 31 </url> 32 <ip> 33 <text>ip</text> 34 <rule>ip</rule> 35 </ip> 36 <mac> 37 <text>mac</text> 38 <rule>mac</rule> 39 </mac> 40 41 <decimal> 42 <text>小數點兩位</text> 43 <rule>decimal</rule> 44 </decimal> 45 <num> 46 <text>數字</text> 47 <rule>num</rule> 48 </num> 49 50 <n> 51 <text>正整數</text> 52 <rule>n</rule> 53 </n> 54 </form> 55 56 <form id="test2"> 57 <name> 58 <text>用戶名</text> 59 <rule>required,min_3,max_20,email</rule> 60 </name> 61 <pwd> 62 <text>密碼</text> 63 <rule>required,min_3,max_20</rule> 64 </pwd> 65 <phone> 66 <text>手機</text> 67 <rule>phone</rule> 68 </phone> 69 </form> 70 </forms>
2.VerifyRegularUtil.java(參考網址:http://www.cnblogs.com/silentjesse/p/3242701.html)

1 /** 2 * 3 */ 4 package com.linker.util; 5 6 import java.util.regex.Pattern; 7 8 /** 9 * Title:VerifyRegularUtil 10 * description: 驗證表單的工具包 11 * company: linker 12 * @author zhanjp 13 * @date 2016年2月22日 上午11:00:52 14 */ 15 public class VerifyRegularUtil { 16 //郵箱 17 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})(\\]?)$"; 18 //手機 19 private String phone = "^[1]+[3,5]+\\d{9}$"; 20 //電話 21 private String tel = "^(\\d{3,4}-)?\\d{6,8}$"; 22 //郵編 23 private String yzbm = "^\\d{6}$"; 24 //身份證 25 private String sfz = "(^\\d{18}$)|(^\\d{15}$)"; 26 27 //url 28 private String url = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"; 29 //ip 30 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]|[*])$"; 31 //物理地址 32 private String mac = "^[A-F0-9]{2}(-[A-F0-9]{2}){5}$"; 33 34 //兩位小數 35 private String decimal = "^[0-9]+(.[0-9]{2})?$"; 36 //數字 37 private String num = "^[0-9]*$"; 38 //正整數 39 private String n = "^\\+?[1-9][0-9]*$"; 40 41 /** 42 * 校驗表單 43 * @param data 44 * @return 45 */ 46 public String verify(String value,String preText,String rule)throws Exception{ 47 String[] rs = rule.split(","); 48 String errorInfo = null; 49 for(String s:rs){ 50 if(s.indexOf("|")<0&&s.indexOf("_")<0){ 51 //包含“|”是指或者的關系,比如輸入框可以輸入郵箱或者手機號,包含“_”,比如min_6指最小6位 52 switch (s) { 53 //需要特殊說明文字的在此添加case 54 case "required": 55 if(value!=null&&value.trim().length()>0){ 56 57 }else{ 58 errorInfo = preText + "不能為空"; 59 } 60 break; 61 //通用說明走else 62 default: 63 errorInfo = verifyByRegular(value,preText,s); 64 break; 65 } 66 if(errorInfo!=null){ 67 //如果已有錯誤信息,則不需要再次循環 68 break; 69 } 70 }else{ 71 if(s.indexOf("|")>=0){ 72 //包含"或者關系",一般"|"和"_"不會共存,在此不做考慮 73 if(s.indexOf("_")>=0){ 74 throw new Exception(preText + "規則配置錯誤"); 75 } 76 String[] s1 = s.split("|"); 77 for(String s2:s1){ 78 errorInfo = verifyByRegular(preText, value, s2); 79 if(errorInfo==null){ 80 break; 81 } 82 } 83 }else if(s.indexOf("_")>=0){ 84 String[] s1 = s.split("_"); 85 if(s1[0].equals("min")){ 86 errorInfo = minLen(preText, value, Integer.parseInt(s1[1])); 87 }else if(s1[0].equals("max")){ 88 errorInfo = maxLen(preText, value, Integer.parseInt(s1[1])); 89 }else{ 90 throw new Exception("暫不支持這種校驗格式:" + s1[0]); 91 } 92 } 93 if(errorInfo!=null){ 94 //如果已有錯誤信息,則不需要再次循環 95 break; 96 } 97 98 } 99 } 100 return errorInfo; 101 } 102 103 /** 104 * 根據正則表達式判斷是否成立 105 * @param preText 必傳,字段名稱 106 * @param value 必傳,字段值 107 * @param r 必傳,校驗類型 108 * @return 109 */ 110 private String verifyByRegular(String value,String preText,String r)throws Exception{ 111 String errorInfo = null; 112 String regex = ""; 113 switch (r) { 114 case "email": 115 regex = email; 116 break; 117 case "phone": 118 regex = phone; 119 break; 120 case "tel": 121 regex = tel; 122 break; 123 case "yzbm": 124 regex = yzbm; 125 break; 126 case "sfz": 127 regex = sfz; 128 break; 129 case "n": 130 regex = n; 131 break; 132 case "url": 133 regex = url; 134 break; 135 case "ip": 136 regex = ip; 137 break; 138 case "mac": 139 regex = mac; 140 break; 141 case "decimal": 142 regex = decimal; 143 break; 144 case "num": 145 regex = num; 146 default: 147 break; 148 } 149 if(regex.equals("")){ 150 throw new Exception("暫不支持這種校驗格式:" + r); 151 }else{ 152 boolean flg = Pattern.matches(regex, value); 153 if(flg){ 154 155 }else{ 156 errorInfo = preText + "格式不正確,請重新檢查!"; 157 } 158 } 159 return errorInfo; 160 } 161 162 163 /** 164 * 校驗最少長度 165 * @param preText 166 * @param value 167 * @param min 168 * @return 169 */ 170 private String minLen(String preText,String value,int min){ 171 String errorInfo = null; 172 if(value!=null&&value.trim().length()>=min){ 173 174 }else{ 175 errorInfo = preText + "最少長度為" + min +"位。"; 176 } 177 return errorInfo; 178 } 179 180 private String maxLen(String preText,String value,int max){ 181 String errorInfo = null; 182 if(value!=null&&value.trim().length()<=max){ 183 184 }else{ 185 errorInfo = preText + "最大長度為" + max +"位。"; 186 } 187 return errorInfo; 188 } 189 190 }
3.Xmlparse4FormVerify.java

1 /** 2 * 3 */ 4 package com.linker.util; 5 6 import java.io.File; 7 import java.io.IOException; 8 import java.util.ArrayList; 9 import java.util.Iterator; 10 import java.util.List; 11 import java.util.Map; 12 import java.util.Set; 13 14 import javax.xml.parsers.DocumentBuilder; 15 import javax.xml.parsers.DocumentBuilderFactory; 16 import javax.xml.parsers.ParserConfigurationException; 17 18 import org.w3c.dom.Document; 19 import org.w3c.dom.Element; 20 import org.w3c.dom.Node; 21 import org.w3c.dom.NodeList; 22 import org.xml.sax.SAXException; 23 24 /** 25 * Title:Xmlparse4FormVerify 26 * description: 讀取xml中配置的表單驗證信息 27 * company: linker 28 * @author zhanjp 29 * @date 2016年2月22日 上午9:33:59 30 */ 31 public class Xmlparse4FormVerify { 32 33 private static DocumentBuilder db = null; 34 35 private static DocumentBuilderFactory dbf = null; 36 37 private static Document dt = null; 38 39 public static Xmlparse4FormVerify xp; 40 41 42 /** 43 * 初始化DocumentBuilder等信息 44 * @return 45 */ 46 public Xmlparse4FormVerify getInstance(){ 47 if(xp==null){ 48 xp = new Xmlparse4FormVerify(); 49 } 50 return xp; 51 } 52 53 static{ 54 try { 55 //返回documentBuilderFactory 56 dbf = DocumentBuilderFactory.newInstance(); 57 58 db = dbf.newDocumentBuilder(); 59 String basePath = new Xmlparse4FormVerify().getClass().getClassLoader().getResource("/").getPath(); 60 File f = new File(basePath + "formVerify.xml"); 61 //獲取xml文件的dom對象 62 dt = db.parse(f); 63 } catch (ParserConfigurationException e) { 64 e.printStackTrace(); 65 System.out.println("class:Xmlparse4FormVerify>>documentBuilder對象初始化失敗。"); 66 } catch (SAXException | IOException e) { 67 // TODO Auto-generated catch block 68 e.printStackTrace(); 69 System.out.println("class:Xmlparse4FormVerify>>解析formVerify.xml文檔失敗"); 70 } 71 } 72 73 /** 74 * 根據表單ID和表單參數進行校驗 75 * @param formId 表單ID 76 * @param pMap 表單參數 77 * @return flag-0:成功,1:失敗; msg-消息 78 * @throws Exception 79 */ 80 public static String verifyForm(String formId,Map<String, String> pMap)throws Exception{ 81 if(dt==null){ 82 throw new Exception("未能正確初始化。"); 83 } 84 String errorInfo = null; 85 //開始解析xml文檔 86 //獲取xml文件跟節點 87 Element element = dt.getDocumentElement(); 88 //獲取根節點下的子節點列表 89 NodeList cList = element.getChildNodes(); 90 List<Node> forms = new ArrayList<>(); 91 for (int i = 0; i < cList.getLength(); i++) { 92 Node tNode = cList.item(i); 93 if(tNode.getNodeName().equals("form")){ 94 forms.add(tNode); 95 } 96 } 97 for (int i = 0; i < forms.size(); i++) { 98 Node node1 = forms.get(i); 99 String nodeId = node1.getAttributes().getNamedItem("id").getNodeValue(); 100 // System.out.println("節點id:" + nodeId+","+"節點name"+node1.getNodeName()); 101 if(nodeId.equals(formId)){ 102 NodeList cList2 = node1.getChildNodes(); 103 //開始校驗 104 Set<String> keys = pMap.keySet(); 105 Iterator<String> iter = keys.iterator(); 106 while (iter.hasNext()) { 107 String key = iter.next(); 108 for (int j = 0; j < cList2.getLength(); j++) { 109 Node node = cList2.item(j); 110 // System.out.println("clist2,node:"+node.getNodeName()); 111 if(node.getNodeName().equals(key)){ 112 String value = pMap.get(key); 113 String preText = ""; 114 String rule = ""; 115 NodeList cList3 = node.getChildNodes(); 116 117 for(int m = 0;m < cList3.getLength(); m++){ 118 if(cList3.item(m).getNodeName()=="text"){ 119 preText = cList3.item(m).getTextContent(); 120 }else if(cList3.item(m).getNodeName()=="rule"){ 121 rule = cList3.item(m).getTextContent(); 122 } 123 } 124 //TODO 校驗 125 errorInfo = new VerifyRegularUtil().verify(value, preText, rule); 126 if(errorInfo!=null){ 127 return errorInfo; 128 } 129 } 130 } 131 132 } 133 break; 134 } 135 } 136 return errorInfo; 137 } 138 }
4.測試代碼:(本項目控制層SpringMvc,可根據自己情況適當更改)

1 @RequestMapping(value="/test2017") 2 public void test2(){ 3 HashMap<String, String> pMap = new HashMap<>(); 4 pMap.put("name", "944593237@qq.com"); 5 pMap.put("pwd", "123456"); 6 pMap.put("phone", "15138456324"); 7 pMap.put("tel", "123456"); 8 pMap.put("yzbm", "3100562"); 9 pMap.put("sfz", "413025199802243366"); 10 pMap.put("url", "http://www.baidu.com"); 11 pMap.put("ip", "172.1.4.113"); 12 pMap.put("mac", "EC-B1-D7-49-20-33"); 13 pMap.put("decimal", "123456.22"); 14 pMap.put("num", "123"); 15 pMap.put("n", "2"); 16 try { 17 String errorInfo = Xmlparse4FormVerify.verifyForm("test2", pMap); 18 if(errorInfo!=null){ 19 System.out.println(errorInfo); 20 }else{ 21 System.out.println("表單驗證通過!"); 22 } 23 } catch (Exception e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 }