SoFunction
Updated on 2025-02-28

JS judges the ID number using regular expressions

Regularly determine whether the ID number is correct

Here is a simple JavaScript function that uses regular expressions to verify that the ID number is formatted correctly:

function isValidIDCard(idCard) {
  // ID card regular expression  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return (idCard);
}

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

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

Use regularity 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 age of the person, and finally compare it with 22.

function is22YearsOld(idCard) {
  // Get the date of birth in the ID number  var birth = (/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$/);
  if (birth == null) {
    // The ID number format is incorrect, directly return false    return false;
  }
  var year = birth[2];
  var month = birth[3];
  var day = birth[4];
  // Calculate the date of birth of this person  var birthday = new Date(year + '-' + month + '-' + day);
  // Calculate the age of this person  var age = new Date().getFullYear() - ();
  if (new Date().getMonth() < () ||
      (new Date().getMonth() == () && new Date().getDate() < ())) {
    age--;
  }
  // Determine whether the age of this person is equal to 22  return age === 22;
  // Determine whether the person is less than 22 years old  return age < 22;
}
(is22YearsOld('110101200102151234')); // true
(is22YearsOld('110101199912312345')); // false

Summarize

This is the article about JS using regular expressions to judge ID number. For more related JS regular judgment content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!