JAVA驗證身份證格式及合法性

旅遊電子商務中,預訂酒店或訂購門票時會以身份證做爲消費憑證,爲了防止客戶誤填身份證帶來沒必要要麻煩,須要驗證碼格式及合法性,代碼以下:spa

   /**
     * 判斷身份證格式
     * 
     * @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 = 0;
        int month = 0;
        int day = 0;

        if (idNum.length() == 15) {

            // 一代身份證

            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("19" + birthDateMather.group(1));
                month = Integer.valueOf(birthDateMather.group(2));
                day = Integer.valueOf(birthDateMather.group(3));

            }

        } else if (idNum.length() == 18) {

            // 二代身份證

            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(1));
                month = Integer.valueOf(birthDateMather.group(2));
                day = Integer.valueOf(birthDateMather.group(3));
            }

        }

        // 年份判斷,100年前至今

        Calendar cal = Calendar.getInstance();

        // 當前年份
        int currentYear = cal.get(Calendar.YEAR);

        if (year <= currentYear - 100 || year > currentYear)
            return false;

        // 月份判斷
        if (month < 1 || month > 12)
            return false;

        // 日期判斷

        // 計算月份天數

        int dayCount = 31;

        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            dayCount = 31;
            break;
        case 2:
            // 2月份判斷是否爲閏年
            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                dayCount = 29;
                break;
            } else {
                dayCount = 28;
                break;
            }
        case 4:
        case 6:
        case 9:
        case 11:
            dayCount = 30;
            break;
        }

        System.out.println(String.format("生日:%d年%d月%d日", year, month, day));

        System.out.println(month + "月份有:" + dayCount + "");

        if (day < 1 || day > dayCount)
            return false;

        return true;
    }
相關文章
相關標籤/搜索