身份证校验最重要的是对应的正则表达式
//正则表达式
public static String strRule="^[1-9][0-7]\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$";
下面提供两种验证方法代码如下
public class CheckIDCard {
private Context mContext;
//正则表达式
public static String strRule="^[1-9][0-7]\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$";
public CheckIDCard(Context context) {
mContext = context;
}
/** 校验身份证 */
public static Pattern idNumPattern = Pattern.compile(strRule);
/** 身份证最后一位校验位 */
public static String[] ID_JIAO_YAN = new String[] { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
/** 身份证前17位系数 */
public static int[] ID_XI_SHU = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
public boolean checkIDCard(String ID){
if(calculIDLast(ID)){
/**校验身份证格式*/
return idNumPattern.matcher(ID).matches();
}else {
return false;
}
}
/**
* 计算身份证最后一位是否正确
* @return
*/
private boolean calculIDLast(String ID) {
boolean flag = false;
if(ID.length()<18){
showToast("请输入正确的二代身份证号码");
return false;
}
char[] chars = ID.toCharArray();
int calculLast=0;
for (int i=0;i<chars.length-1;i++){
calculLast += Integer.parseInt(chars[i]+"")*this.ID_XI_SHU[i];
}
Log.i("calculLast==",calculLast+"");
int i = calculLast % 11;
String a = this.ID_JIAO_YAN[i];
String b = chars[chars.length-1]+"";
if (a.toUpperCase().equals(b.toUpperCase())){
flag = true;
}
return flag;
}
private void showToast(String msg) {
Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}
}
仅供参考,多多指教,谢谢啦!