<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js验证身份证</title> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> </head> <body> <div class="identity"> 身份证号码:<input type="text" class="input" name="num" id="verify" /> <input type="button" value="验证" onclick='check_verify()' /> </div> </body> <script> function verification(idCard) { idCard = idCard.replace(/ /g, ""); if (idCard.length == 15) { return isValidityBrithBy15IdCard(idCard); } else if (idCard.length == 18) { var a_idCard = idCard.split(""); if (isValidityBrithBy18IdCard(idCard) && validate(a_idCard)) { return true; } else { return false; } } else { return false; } return true; } //判断身份证号18位时最后一位是否正确 function validate(a_idCard) { var ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; //身份证验证位值.10代表X var yinzi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]; var sum = 0; if (a_idCard[17].toLowerCase() == 'x') { a_idCard[17] = 10; } for (var i = 0; i < 17; i++) { sum += yinzi[i] * a_idCard[i]; } var valCodePosition = sum % 11; if (a_idCard[17] == ValideCode[valCodePosition]) { return true; } else { return false; } } function isValidityBrithBy18IdCard(idCard18) { var year = idCard18.substring(6, 10); var month = idCard18.substring(10, 12); var day = idCard18.substring(12, 14); var temp_date = new Date(); temp_date.setYear(year); temp_date.setMonth(parseInt(month, 10) - 1); temp_date.setDate(parseInt(day, 10)); if (temp_date.getFullYear() != parseInt(year, 10) || temp_date.getMonth() != parseInt(month, 10) - 1 || temp_date.getDate() != parseInt(day, 10)) { return true; } else { return true; } } function isValidityBrithBy15IdCard(idCard15) { var year = idCard15.substring(6, 8); var month = idCard15.substring(8, 10); var day = idCard15.substring(10, 12); var temp_date = new Date(); temp_date.setYear(year); temp_date.setMonth(parseInt(month, 10) - 1); temp_date.setDate(parseInt(day, 10)); if (temp_date.getYear() != parseInt(year, 10) || temp_date.getMonth() != parseInt(month, 10) - 1 || temp_date.getDate() != parseInt(day, 10)) { return true; } else { return true; } } function check_verify() { var verify = $("#verify").val(); var res = verification(verify); if (res == true) { alert('正确'); } else { alert('错误'); } } </script> </html>