javascript

vue+element 身份證號碼以及有效性校驗 適用 15位 或18位

  1. data () {
  2. let idCardValidity = (rule, code, callback) => {
  3. var city = { 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: "新疆", 71: "臺灣", 81: "香港", 82: "澳門", 91: "國外 " };
  4. var tip = ""
  5. var pass = true
  6. if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
  7. tip = "身份證號格式錯誤"
  8. pass = false;
  9. } else if (!city[code.substr(0, 2)]) {
  10. tip = "地址編碼錯誤"
  11. pass = false
  12. } else {
  13. // 18位身份證需要驗證最後一位校驗位
  14. if (code.length === 18) {
  15. code = code.split('')
  16. // ∑(ai×Wi)(mod 11)
  17. // 加權因子
  18. var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  19. // 校驗位
  20. var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
  21. var sum = 0
  22. var ai = 0
  23. var wi = 0
  24. for (var i = 0; i < 17; i++) {
  25. ai = code[i]
  26. wi = factor[i]
  27. sum += ai * wi
  28. }
  29. var last = parity[sum % 11];
  30. if (parity[sum % 11] != code[17]) {
  31. tip = "校驗位錯誤"
  32. pass = false
  33. }
  34. }
  35. }
  36. if (!pass) {
  37. callback(new Error(tip))
  38. } else {
  39. callback()
  40. }
  41. // if (!pass) alert(tip)
  42. // return pass
  43. }
  44. return {
  45. personInfo: {
  46. idCard: "",
  47. },
  48. rules: {
  49. idCard: [{ required: true, message: '請輸入證件號', trigger: 'blur' },
  50. {
  51. pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
  52. message: '請輸入正確的證件號'
  53. },
  54. { validator: idCardValidity, trigger: 'blur' }],
  55. }
  56. }
  57. },

1.規則方法寫在 data裡 return之前。

2. 身份證有效性校驗規則來源與百度

校驗公示:∑(ai×Wi)(mod 11)

https://baike.baidu.com/item/%E6%9C%89%E6%95%88%E8%BA%AB%E4%BB%BD%E8%AF%81%E4%BB%B6/5039723?fr=aladdin

 

本文章已修改原文用詞符合繁體字使用者習慣使其容易閱讀

版權宣告:此處為CSDN博主「優秀的金大大」的原創文章,依據CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。

原文連結:https://blog.csdn.net/qq_31173561/article/details/101273159