根據身份證號碼推算出最後一位的正確性,如果不正確還會給出正確結果,非常有意思的一斷程序。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>javascript 18位身份證號碼最後一位校驗碼</title> </head> <body> <script> function getIDChar18(id) { var arr = id.split(''), sum = 0, vc = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; for (var i = 0; i < 17; i++) sum += vc[i] * parseInt(arr[i]); return ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'][sum % 11]; } function ValidID(id) { if (/^\d{18}$/.test(id)) { var c = id.charAt(17), rc = getIDChar18(id); if (c == rc) showRst('您輸入的18位身份證號碼正確!<br>生日:' + id.substr(6, 8) + '<br>性別:' + ['女', '男'][parseInt(id.charAt(16)) % 2]); else showRst('您輸入的18位身份證號碼檢驗碼錯誤,18位校驗碼應該為' + rc + '!'); } else showRst('請輸入18位數字的身份證號碼!'); } function showRst(msg) {document.getElementById('rst').innerHTML=msg } </script> <input type="text" onblur="ValidID(this.value)" /> <div id="rst"></div> </body> </html>