身份證號碼格式驗證

/**
 * 身份證驗證
 *@param certNo  號碼內容
 *@return 是否有效 null和"" 都是false
 */
public static boolean isIDCard(String certNo){
    if(certNo == null || (certNo.length() != 15 && certNo.length() != 18))
        return false;
    final char[] cs = certNo.toUpperCase().toCharArray();
    //校驗位數
    int power = 0;
    for(int i=0; i<cs.length; i++){
        if(i==cs.length-1 && cs[i] == 'X')
            break;//最後一位可以 是X或x
        if(cs[i]<'0' || cs[i]>'9')
            return false;
        if(i < cs.length -1){
            power += (cs[i] - '0') * POWER_LIST[i];
        }
    }

    //校驗區位碼
    if(!zoneNum.containsKey(Integer.valueOf(certNo.substring(0,2)))){
        return false;
    }

    //校驗年份
    String year = certNo.length() == 15 ? getIdcardCalendar() + certNo.substring(6,8) :certNo.substring(6, 10);

    final int iyear = Integer.parseInt(year);
    if(iyear < 1900 || iyear > Calendar.getInstance().get(Calendar.YEAR))
        return false;//1900年的PASS,超過今年的PASS

    //校驗月份
    String month = certNo.length() == 15 ? certNo.substring(8, 10) : certNo.substring(10,12);
    final int imonth = Integer.parseInt(month);
    if(imonth <1 || imonth >12){
        return false;
    }

    //校驗天數
    String day = certNo.length() ==15 ? certNo.substring(10, 12) : certNo.substring(12, 14);
    final int iday = Integer.parseInt(day);
    if(iday < 1 || iday > 31)
        return false;

    //校驗"校驗碼"
    if(certNo.length() == 15)
        return true;
    return cs[cs.length -1 ] == PARITYBIT[power % 11];
}
發佈了34 篇原創文章 · 獲贊 39 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章