javascript 正则判断身份证号 in javascript

You can use the following regular expression to validate Chinese ID cards in JavaScript:

index.tsx
function validateIDCard(idCard) {
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(idCard);
}
119 chars
5 lines

This regular expression checks for either 15 digits or 18 digits, or 17 digits followed by either a digit or the letter X or x. You can use this function to validate ID cards in your JavaScript code as shown below:

index.tsx
var idCard = "12345678901234567X";
if (validateIDCard(idCard)) {
  console.log("Valid ID card");
} else {
  console.log("Invalid ID card");
}
142 chars
7 lines

In this example, we pass a sample ID card number to the validateIDCard() function and check if it is valid or not. The function returns true if the ID card is valid, and false otherwise.

gistlibby LogSnag