From 27c2f609698a5adfaa7fd72610355f7be017ec56 Mon Sep 17 00:00:00 2001 From: neehow <7135209+neehow@users.noreply.github.com> Date: Tue, 9 Apr 2019 00:18:07 +0800 Subject: [PATCH] add readme and source --- README.md | 18 +++++++++++++++++- index.js | 17 +++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 index.js diff --git a/README.md b/README.md index d54694d..24328c0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,18 @@ # is-valid-id-card -一个校验身份证号是否符合规则的方法。(A function to test if a Chinese ID card is valid.) +一个校验身份证号是否符合规则的方法。(A function to test if a Chinese ID card is valid.) +校验身份证是否符合标准 +参考国家标准:[GB 11643-1999](http://www.gb688.cn/bzgk/gb/newGbInfo?hcno=080D6FBF2BB468F9007657F26D60013E),只有18位身份证才符合标准 +参考了此文章:https://blog.csdn.net/qq_41589580/article/details/81040772 +暂时未做每月不同天数及闰年的校验,如生日是2月31号也返回true。今后有空可能会加上此校验。 +注意:身份证号符合规则,只是该身份证号符合国家标准中的规则,并不意味着该身份证号真实存在。 + +## Installation +npm install is-valid-id-card --save + +## Examples +``` +const isValidIDCard = require('is-valid-id-card') +console.log(isValidIDCard('')) // false +console.log(isValidIDCard('123456')) // false +console.log(isValidIDCard('11012119880808223x')) // true +``` \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..c909ec0 --- /dev/null +++ b/index.js @@ -0,0 +1,17 @@ +function isValidIDCard (idNo) { + // 不能用数字,有精度问题 + if (!idNo || typeof idNo !== 'string') return false + idNo = idNo.trim() + if (idNo.length !== 18) return false + // 正则校验 + var rIdNo = /^(11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65)\d{4}(18|19|20)\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}[0-9xX]$/ + if (!rIdNo.test(idNo)) return false + // 加权因子 + var weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1] + var nums = idNo.split('').map(str => +str.replace(/x/i, '10')) + var numsWithWeight = nums.map((n, i) => n * weights[i]) + var sum = numsWithWeight.reduce((acc, cur) => acc + cur) + return sum % 11 === 1 +} + +module.exports = isValidIDCard