所有工具類
一個 Java 驗證 的工具類 支持各種類型的驗證 在項目中大量使用
引用類
zj.check.bean.IdCard
package zj.check.util; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import zj.check.bean.IdCard; import zj.date.util.DateUtil; import zj.java.util.JavaUtil; import zj.reflect.util.TypeUtil; import zj.regex.util.RegexUtil; /** * 驗證工具類 * * @version 1.00 (2014.09.15) * @author SHNKCS 張軍 {@link <a target=_blank href="http://m.eyofj.com">張軍個人網站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">張軍QQ空間</a>} */ public class CheckUtil implements Serializable { private static final long serialVersionUID = 1L; /** * 判斷字符串是否為空 * * @param value * 校驗字符串 * @return true:空或"",false:非空并且非"" */ public static boolean isNull(String value) { return value == null || (value = value.trim()).equals("") || value.length() == 0 || value.matches("\\s*"); } /** * 判斷字符串是否為空 * * @param value * 校驗字符串 * @return true:非空并且非"",false:空或"" */ public static boolean isNotNull(String value) { return !isNull(value); } /** * 判斷對象是否為空 * * @param value * 校驗對象 * @return true:空,false:非空 */ public static boolean isNull(Object value) { return value == null || "".equals(value); } /** * 檢查多個字符串是否為""或者null * * @param values * 可變數組 * @return true:全部不為null且不為"" false:其中有為null或者為""的字符串 */ public static boolean isContainsNulls(String... values) { if (values == null) return true; for (String value : values) { if (value == null || value.trim().length() == 0) { return true; } } return false; } /** * 判斷是否是正數 * * @param value * 校驗字符串 * @return true:正數,false:非正數 */ public static boolean isPlusNum(String value) { if (isNull(value)) return false; return RegexUtil.getMatcherResult("^[0-9]+$", value); } /** * 判斷是否大于0的正數 * * @param value * 校驗字符串 * @return true:正數,false:非正數 */ public static boolean isPlusNumGtZero(String value) { if (isNull(value)) return false; return RegexUtil.getMatcherResult("^[1-9][0-9]*$", value); } /** * 判斷是否大于0的正數 * * @param value * 校驗字符串 * @return true:正數,false:非正數 */ public static boolean isNumber(String value) { if (isNull(value)) return false; return RegexUtil.getMatcherResult("^(([0-9]+)|(-[1-9][0-9]+))(\\.?[0-9]*)$", value); } /** * 銀行卡號驗證 * * @param value * 校驗字符串 * @return true:是銀行卡號,false:非銀行卡號 */ public static boolean checkBankCard(String value) { char bit = getBankCardCheckCode(value.substring(0, value.length() - 1)); if (bit == 'N') { return false; } return value.charAt(value.length() - 1) == bit; } /** * 銀行卡號驗證 * * @param value * 校驗字符串 * @return 非'N':是銀行卡號,'N':非銀行卡號 */ private static char getBankCardCheckCode(String value) { if (value == null || value.trim().length() == 0 || !value.matches("\\d+")) { // 如果傳的不是數據返回N return 'N'; } char[] chs = value.trim().toCharArray(); int luhmSum = 0; for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) { int k = chs[i] - '0'; if (j % 2 == 0) { k *= 2; k = k / 10 + k % 10; } luhmSum += k; } return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0'); } /** * 字符對應的數據庫長度,防止溢出,返回數據庫字段最大長度 * * @param value * 校驗字符串 * @return 字符對應的數據庫長度 */ public static int getTextLengthByDB(String value) { if (CheckUtil.isNull(value)) { return 0; } int valueLength = 0; String chinese = "[\u0391-\uFFE5]"; /* 獲取字段值的長度,如果含中文字符,則每個中文字符長度為2,否則為1 */ for (int i = 0; i < value.length(); i++) { /* 獲取一個字符 */ String temp = value.substring(i, i + 1); /* 判斷是否為中文字符 */ if (temp.matches(chinese)) { /* 中文字符長度為3 */ valueLength += 3; } else { /* 其他字符長度為1 */ valueLength += 1; } } return valueLength; } /** * 截取的數據庫長度字符串 * * @param value * 校驗字符串 * @param dbLength * 數據庫長度 * @param chineseConvertLength * 中文轉換長度 * @return 截取的數據庫長度字符串 */ public static String getTextLengthStopByDB(String value, int dbLength, int chineseConvertLength) { if (CheckUtil.isNull(value)) { return null; } int valueLength = 0; /* 獲取字段值的長度,如果含中文字符,則每個中文字符長度為chineseConvertLength,否則為1 */ String newText = ""; for (int i = 0; i < value.length(); i++) { /* 獲取一個字符 */ String temp = value.substring(i, i + 1); /* 判斷是否為中文字符 */ if (isChinese(temp)) { /* 中文字符長度為chineseConvertLength */ valueLength += chineseConvertLength; } else { /* 其他字符長度為1 */ valueLength += 1; } if (valueLength > dbLength) { return newText; } newText += temp; } return newText; } /** * 字符對應的數據庫長度字符串,防止溢出 * * @param value * 校驗字符串 * @param dbLength * 數據庫長度 * @return 截取的數據庫長度字符串 */ public static String getTextLengthStopByDB(String value, int dbLength) { return getTextLengthStopByDB(value, dbLength, 3); } /** * 驗證是否是中文字符 * * @param value * 校驗字符串 * @return true:是中文,false:非中文 */ public static boolean isChinese(String value) { String chinese = "[\u0391-\uFFE5]+"; if (value.matches(chinese)) { return true; } return false; } /** * 手機號碼驗證:1、手機號碼位數必須為11位阿拉伯數字;2、手機號碼第一位必須為“13、14、15、17或18”開頭。 * * @param value * 校驗字符串 * @return true:通過,false:不通過 */ public static boolean isValidMobile(String value) { Pattern p = Pattern.compile("^(1[34578])\\d{9}$"); Matcher match = p.matcher(value); return match.matches(); } /** * 驗證身份證號碼 * * @param value * 校驗字符串 * @return 返回校驗結果map * */ public static Map<String, String> isIdCard(String value) { Map<String, String> map = new HashMap<String, String>(); if (CheckUtil.isNull(value)) { map.put(IdCard.ERROR_MSG, "身份證號不能為空"); return map; } // 轉換為小寫 String code = value.toUpperCase(); if (code.length() != 15 && code.length() != 18) { map.put(IdCard.ERROR_MSG, "身份證號長度必須是15位或18位"); return map; } // 生日 String birthday = null; // 性別 int sex = 0; // 省代碼 String provinceCode = null; // 省市代碼 String countyCode = null; // 省市區代碼 String areaCode = null; // 省 String provinceName = null; // 省市 String countyName = null; // 省市區 String areaName = null; // 驗證 if (code.length() == 15) { // 15位身份證號,身份證15位時,次序為省(3位)市(3位)年(2位)月(2位)日(2位)校驗位(3位),皆為數字 // 在java、js中,索引從1開始,m.groupCount()為總長度[括號數],索引為0時為被驗證的字符串 Matcher group = RegexUtil.getMatcher("^(\\d{6})(\\d{2})(\\d{2})(\\d{2})(\\d{3})$", code); if (!group.find()) { map.put(IdCard.ERROR_MSG, "身份證號格式錯誤"); return map; } // 性別 sex = TypeUtil.Primitive.intValue(group.group(group.groupCount())); // 生日 birthday = "19" + group.group(2) + "-" + group.group(3) + "-" + group.group(4); } else if (code.length() == 18) { // 18位身份證號,身份證18位時,次序為省(3位)市(3位)年(4位)月(2位)日(2位)校驗位(4位),校驗位末尾可能為X Matcher group = RegexUtil.getMatcher("^\\d{6}(18|19|20)?(\\d{2})(0[1-9]|1[12])(0[1-9]|[12]\\d|3[01])(\\d{3})(\\d|x|X)$", code); if (!group.find()) { map.put(IdCard.ERROR_MSG, "身份證號格式錯誤"); return map; } // 性別 sex = TypeUtil.Primitive.intValue(group.group(group.groupCount() - 2)); // 生日 birthday = group.group(1) + group.group(2) + "-" + group.group(3) + "-" + group.group(4); // 18位身份證需要驗證最后一位校驗位開始 char[] codeAry = code.toCharArray(); String lastCodeCheck[] = new String[codeAry.length]; for (int i = 0; i < lastCodeCheck.length; i++) { lastCodeCheck[i] = JavaUtil.objToStr(codeAry[i]); } // ∑(ai×Wi)(mod 11) // 加權因子 int[] factor = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 校驗位 String[] parity = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }; int sum = 0; int ai = 0; int wi = 0; // 循環前17位數字 for (int i = 0; i < 17; i++) { ai = TypeUtil.Primitive.intValue(lastCodeCheck[i]); wi = factor[i]; sum += ai * wi; } String last = parity[sum % 11]; // 最后一位數判斷 String codeLast = lastCodeCheck[17]; if (!last.equals(codeLast)) { map.put(IdCard.ERROR_MSG, "校驗位錯誤"); return map; } // 18位身份證需要驗證最后一位校驗位結束 } // 省代碼 provinceCode = code.substring(0, 2); // 省市代碼 countyCode = code.substring(0, 4); // 省市區代碼 areaCode = code.substring(0, 6); // 省名稱 provinceName = IdCard._CITY.get(provinceCode); // 省市名稱 countyName = IdCard._CITY.get(countyCode); // 省市區名稱 areaName = IdCard._CITY.get(areaCode); if (CheckUtil.isNull(provinceName)) { map.put(IdCard.ERROR_MSG, "開頭2位地址編碼錯誤"); return map; } if (CheckUtil.isNull(countyName)) { map.put(IdCard.ERROR_MSG, "開頭4位地址編碼錯誤"); return map; } if (CheckUtil.isNull(areaName)) { map.put(IdCard.ERROR_MSG, "開頭6位地址編碼錯誤"); return map; } int sexCode = sex % 2; map.put(IdCard.SEX_CODE, JavaUtil.objToStr(sexCode)); map.put(IdCard.SEX_NAME, sexCode == 0 ? "女" : "男"); map.put(IdCard.BIRTH_DAY, birthday); map.put(IdCard.PROVINCE_CODE, provinceCode); map.put(IdCard.COUNTY_CODE, countyCode); map.put(IdCard.AREA_CODE, areaCode); map.put(IdCard.PROVINCE_NAME, provinceName); map.put(IdCard.COUNTY_NAME, countyName); map.put(IdCard.AREA_NAME, areaName); return map; } /** * 驗證身份證號碼 * * @param value * 校驗字符串 * @return 返回校驗結果map * <p> * key:sex,value:1:男,0:女 * </p> * <p> * key:errorMsg,value:錯誤提示信息 * </p> * <p> * key:birthday,value:生日 * </p> * <p> * key:success,value:true:成功,false:失敗 * </p> * */ public static Map<String, Object> isValidIdNo(String value) { Map<String, Object> result = new HashMap<String, Object>(); result.put("success", "false"); Pattern p = Pattern.compile("^([\\d]{6})([\\d]{8})([\\d]{3})([\\d|x|X])$"); Matcher match = p.matcher(value); if (match.matches()) { match.reset(); // 取得生日 while (match.find()) { String birthday = match.group(2); if (DateUtil.parseDate(birthday) == null) { result.put("errorMsg", "生日不正確"); return result; } result.put("birthday", DateUtil.parseDate(birthday)); // 取得性別 String sex = match.group(3); result.put("sex", String.valueOf(Integer.parseInt(sex) % 2)); // while (match.find()) { // for (int i = 0; i <= match.groupCount(); i++) { // System.out.println("索引(" + i + ")→" + match.group(i)); // } // } } result.put("success", "true"); } else { result.put("errorMsg", "身份證號碼格式不正確"); } return result; } /** * 校驗郵箱格式 * * @param obj * 校驗對象 * @return true:正確,false:非正確 */ public static boolean isEmail(Object obj) { return isEmail(obj, ";"); } /** * 校驗郵箱格式 * * @param obj * 校驗對象 * @param split * 分割字符串 * @return true:正確,false:非正確 */ @SuppressWarnings("unchecked") public static boolean isEmail(Object obj, String split) { Collection<String> values = null; if (obj instanceof String) { values = Arrays.asList(JavaUtil.split(String.valueOf(obj), split)); } else if (obj instanceof Collection) { values = ((Collection<String>) obj); } else if (obj instanceof String[]) { values = Arrays.asList((String[]) obj); } if (values == null || values.size() == 0) { return false; } // str="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$"; Pattern p = Pattern.compile("^([a-zA-Z0-9_\\.-]+)@([\\da-zA-Z\\.-]+)\\.([a-zA-Z\\.]{2,6})$"); Iterator<String> it = values.iterator(); while (it.hasNext()) { Matcher match = p.matcher(it.next()); if (!match.matches()) { return false; } } return true; } }
本文為張軍原創文章,轉載無需和我聯系,但請注明來自張軍的軍軍小站,個人博客http://m.eyofj.com
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
