JAVA校验身份证号码

/**

*

*/

import java.text.SimpleDateFormat;

/**

* @author liu

* @version 2017年4月5日 下午4:11:07

* @purpose

*/

public class Snippet {

private static boolean checkDate(String year, String month, String day) {

SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");

try {

String s3 = year + month + day;

simpledateformat.setLenient(false);

simpledateformat.parse(s3);

} catch (java.text.ParseException parseexception) {

return false;

}

return true;

}

/**

* 校验身份证

*

* @param certiCode

*            待校验身份证

* @return 0--校验成功; 1--位数不对; 2--生日格式不对 ; 3--校验位不对 ; 4--其他异常;5--字符异常;

* @param certiCode

* @return

*/

public static int checkCertiCode(String certiCode) {

try {

if (certiCode == null || certiCode.length() != 15

&& certiCode.length() != 18)

return 1;

String s1;

String s2;

String s3;

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

if (!checkFigure(certiCode)) {

return 5;

}

s1 = "19" + certiCode.substring(6, 10);

s2 = certiCode.substring(8, 10);

s3 = certiCode.substring(10, 12);

if (!checkDate(s1, s2, s3))

return 2;

}

if (certiCode.length() == 18) {

if (!checkFigure(certiCode.substring(0, 17))) {

return 5;

}

s1 = certiCode.substring(6, 10);

s2 = certiCode.substring(10, 12);

s3 = certiCode.substring(12, 14);

if (!checkDate(s1, s2, s3))

return 2;

if (!checkIDParityBit(certiCode))

return 3;

}

} catch (Exception exception) {

return 4;

}

return 0;

}

/**

* 检查字符串是否全为数字

*

* @param certiCode

* @return

*/

private static boolean checkFigure(String certiCode) {

try {

Long.parseLong(certiCode);

} catch (NumberFormatException e) {

return false;

}

return true;

}

private static boolean checkIDParityBit(String certiCode) {

boolean flag = false;

if (certiCode == null || "".equals(certiCode))

return false;

int ai[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };

if (certiCode.length() == 18) {

int i = 0;

for (int k = 0; k < 18; k++) {

char c = certiCode.charAt(k);

int j;

if (c == 'X'||c == 'x')

j = 10;

else if (c <= '9' || c >= '0')

j = c - 48;

else

return flag;

i += j * ai[k];

}

if (i % 11 == 1)

flag = true;

}

return flag;

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,780评论 18 399
  • 一、 1、请用Java写一个冒泡排序方法 【参考答案】 public static void Bubble(int...
    独云阅读 1,426评论 0 6
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 1,526评论 0 3
  • 2016.12.17 近3个月的目标是: 升级我的伴侣和增加财富。用种子创造更加美好的工作和生活。我怀着无比喜悦、...
    朵儿2016阅读 209评论 0 0