function checkCode() {//社会统一验证码 var code = document.getElementById("userName").value; if(code.length != 18&&code.length != 9){ alert("社会信用代码或者组织机构代码长度错误!"); return false; } if(code.length == 9){ var ws = [3, 7, 9, 10, 5, 8, 4, 2]; var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var reg = /^([0-9A-Z]){9}$/; if (!reg.test(code)) { alert("组织机构代码错误"); return false; } var sum = 0; for (var i = 0; i < 8; i++) { sum += str.indexOf(code.charAt(i)) * ws[i]; } alert(code.substring(8,9)); var C9 = 11 - (sum % 11); if (C9 == 11) { C9='0'; } else if (C9 == 10) { C9='X'; } alert(C9); if(C9!=code.substring(8,9)){ alert("组织机构代码错误"); return false; } } if(code.length == 18){ var reg = /^([0-9ABCDEFGHJKLMNPQRTUWXY]{2})([0-9]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-9Y])$/; if(!reg.test(code)){ alert("社会信用代码校验错误!"); return false; } var str = '0123456789ABCDEFGHJKLMNPQRTUWXY'; var ws =[1,3,9,27,19,26,16,17,20,29,25,13,8,24,10,30,28]; var codes = new Array(); codes[0] = code.substr(0,code.length-1); codes[1] = code.substr(code.length-1,code.length); var sum = 0; for(var i=0;i<17;i++){ sum += str.indexOf(codes[0].charAt(i)) * ws[i]; } var c18 = 31 - (sum % 31); if(c18 == 31){ alert("第18位 == 31"); c18 = 'Y'; }else if(c18 == 30){ alert("第18位 == 30"); c18 = '0'; } if(c18 != codes[1]){ alert("社会信用代码有误!"+c18); return false; } } }
来源:http://www.cnblogs.com/caozengling/p/6257368.html