天天看点

身份证号码格式验证

/**
 * 身份证验证
 *@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];
}      

继续阅读