正则验证、计算身份证

1.校验15、18位身份证
const regCart = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;

缺点:未校验2月份的天数不超过28


2.校验手机号码
const regExp = /^1(3|4|5|7|8)\d{9}$/;

3.根据身份证计算出生日期、年龄、性别
calculateCard(str) {
  const ret = {
    birthday: null,
    age: null,
    gender: null,
  };
  const len = str.length;
  if (len === 15 || len === 18) {
    // 计算出生日期 - birthday
    if (len === 18) {
      ret.birthday = `${str.substr(6, 4)}-${str.substr(10, 2)}-${str.substr(12, 2)}`;
    }
    if (len === 15) {
      ret.birthday = `19${str.substr(6, 2)}-${str.substr(8, 2)}-${str.substr(10, 2)}`;
    }
    // 计算年龄 - age
    const ageVal = new Date(ret.birthday);
    const nowDateTime = new Date();
    ret.age = nowDateTime.getFullYear() - ageVal.getFullYear();
    // 月、天的差异
    if (nowDateTime.getMonth() < ageVal.getMonth() ||
     (nowDateTime.getMonth() === ageVal.getMonth() && nowDateTime.getDate() < ageVal.getDate())) {
      ret.age -= 1;
    }
    // 计算性别 - gender
    ret.gender = (parseInt(str.substr(16, 1), 10) % 2 === 1) ? '男' : '女';
  }
  return ret;
},
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用正则表达式可以很方便地校验身份证是否合法。下面是一个简单的实现示例: ```java public class IDCardValidator { private static final String REGEX_ID_CARD = "^\\d{17}(\\d|x|X)$"; public static boolean isValidIDCard(String idCard) { boolean isValid = false; if (idCard != null && idCard.matches(REGEX_ID_CARD)) { int[] coefficientArr = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; int[] validateCodeArr = {1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2}; int sum = 0; for (int i = 0; i < 17; i++) { int num = Integer.parseInt(idCard.substring(i, i + 1)); sum += num * coefficientArr[i]; } int validateCodeIndex = sum % 11; char validateCode = validateCodeArr[validateCodeIndex] == 'X' ? 'X' : (char) (validateCodeArr[validateCodeIndex] + '0'); isValid = validateCode == idCard.charAt(17); } return isValid; } public static void main(String[] args) { String idCard = "44030819990101001X"; System.out.println(isValidIDCard(idCard)); // 输出true } } ``` 上述代码定义了一个IDCardValidator类,其中isValidIDCard(String idCard)方法使用正则表达式校验身份证号是否合法。首先,通过.matches()方法确保身份证号满足格式要求。然后,根据中国身份证号的校验规则,按照权重因子计算身份证号的验证位,最后将计算得到的验证位与身份证号的最后一位进行比较,若相等则身份证号合法。最后,在main方法中输入一个身份证号进行测试,输出结果为true表示身份证号合法。 以上便是使用Java正则表达式校验身份证是否合法的简单实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值