这是一个没有验证行政区代码的,所以这个不算完全,但是我们在做实际应用时可以加上,这里我没加。
源码如下仅供参考.
package ibees.validator;
import java.util.regex.Pattern;
/**
* 常用的验证,source charset utf-8
*
* @author hhzxj2008
* */
public class CommonValidator {
public static boolean validatePersonalId(String personalId) {
if ((personalId == null) || ((personalId.length() != 15) &&
(personalId.length() != 18))) {
return false;
}
int personalIdLength = personalId.length();
String regex = "[1-8]{1}[0-9]{" + (personalIdLength-2) + "}[0-9X]";
Pattern pattern = Pattern.compile(regex);
if (!pattern.matcher(personalId).matches()) {
return false;
}
// 将老身份证转换为新身份证
if (personalIdLength == 15) {
StringBuffer stringBuffer = new StringBuffer(personalId);
stringBuffer.insert(6, "19");
personalId = stringBuffer.toString();
}
// 规则
byte[] poss = { 2, 4, 8, 5, 10, 9, 7, 3, 6, 1, 2, 4, 8, 5, 10, 9, 7 };
char[] possibleLast = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
int last = 0;
int[] pid = new int[18];
for (int i = 1; i < 18; i++){
int j = 17 - i;
pid[i - 1] = Integer.parseInt(personalId.substring(j, j + 1));
}
for (int i = 0; i < 17; i++){
last += poss[i] * pid[i];
}
last = last % 11;
if(possibleLast[last] == personalId.charAt(17)){
return true;
}
return false;
}
调用此方法即可验证身份证号码,正确率挺高的。