js regular judgment on ID number

1.JS regular code determines whether the ID number is correct

The following is a simple JavaScript function that uses regular expressions to verify that the ID number is in the correct format:

function isValidIDCard(idCard) {
  // 身份证正则表达式
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(idCard);
}

The above code only verifies whether the format of the ID number is correct, but does not verify whether the ID number itself is legal. If you need to verify the legitimacy of the ID number, you can use a third-party library or online service. 

console.log(isValidIDCard('110101199003072733')); // true
console.log(isValidIDCard('11010119900307273X')); // true
console.log(isValidIDCard('1101011990030727')); // false
console.log(isValidIDCard('110101199003072734')); // false

2.js uses regular rules to determine whether the current ID number is 22 years old

To determine whether the ID number corresponds to a 22-year-old person, you need to first obtain the date of birth in the ID number, then calculate the person's age, and finally compare it with 22.

function is22YearsOld(idCard) {
  // 获取身份证号码中的出生日期
  var birth = idCard.match(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$/);
  if (birth == null) {
    // 身份证号码格式不正确,直接返回 false
    return false;
  }
  var year = birth[2];
  var month = birth[3];
  var day = birth[4];
  // 计算此人的出生日期
  var birthday = new Date(year + '-' + month + '-' + day);
  // 计算此人的年龄
  var age = new Date().getFullYear() - birthday.getFullYear();
  if (new Date().getMonth() < birthday.getMonth() ||
      (new Date().getMonth() == birthday.getMonth() && new Date().getDate() < birthday.getDate())) {
    age--;
  }
  // 判断此人的年龄是否等于 22
  return age === 22;
   
  // 判断此人年龄是否小于 22
  return age < 22;
}
console.log(is22YearsOld('110101200102151234')); // true
console.log(is22YearsOld('110101199912312345')); // false

Guess you like

Origin blog.csdn.net/m0_63873004/article/details/129041876