JAVA验证身份证格式及合法性

旅游电子商务中,预订酒店或订购门票时会以身份证作为消费凭证,为了防止客户误填身份证带来不必要麻烦,需要验证码格式及合法性,代码如下:

   /**
* 判断身份证格式
*
* @param idNum
* @return
*/
public static boolean isIdNum(String idNum) { // 中国公民身份证格式:长度为15或18位,最后一位可以为字母
Pattern idNumPattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])"); // 格式验证
if (!idNumPattern.matcher(idNum).matches())
return false; // 合法性验证 int year = ;
int month = ;
int day = ; if (idNum.length() == ) { // 一代身份证 System.out.println("一代身份证:" + idNum); // 提取身份证上的前6位以及出生年月日
Pattern birthDatePattern = Pattern.compile("\\d{6}(\\d{2})(\\d{2})(\\d{2}).*"); Matcher birthDateMather = birthDatePattern.matcher(idNum); if (birthDateMather.find()) { year = Integer.valueOf("" + birthDateMather.group());
month = Integer.valueOf(birthDateMather.group());
day = Integer.valueOf(birthDateMather.group()); } } else if (idNum.length() == ) { // 二代身份证 System.out.println("二代身份证:" + idNum); // 提取身份证上的前6位以及出生年月日
Pattern birthDatePattern = Pattern.compile("\\d{6}(\\d{4})(\\d{2})(\\d{2}).*"); Matcher birthDateMather = birthDatePattern.matcher(idNum); if (birthDateMather.find()) { year = Integer.valueOf(birthDateMather.group());
month = Integer.valueOf(birthDateMather.group());
day = Integer.valueOf(birthDateMather.group());
} } // 年份判断,100年前至今 Calendar cal = Calendar.getInstance(); // 当前年份
int currentYear = cal.get(Calendar.YEAR); if (year <= currentYear - || year > currentYear)
return false; // 月份判断
if (month < || month > )
return false; // 日期判断 // 计算月份天数 int dayCount = ; switch (month) {
case :
case :
case :
case :
case :
case :
case :
dayCount = ;
break;
case :
// 2月份判断是否为闰年
if ((year % == && year % != ) || (year % == )) {
dayCount = ;
break;
} else {
dayCount = ;
break;
}
case :
case :
case :
case :
dayCount = ;
break;
} System.out.println(String.format("生日:%d年%d月%d日", year, month, day)); System.out.println(month + "月份有:" + dayCount + "天"); if (day < || day > dayCount)
return false; return true;
}
上一篇:C# Invoke方法


下一篇:POJ 3107 Godfather(树的重心)