支持带横杠 (xxxxxxx-X)/不带横杠 (xxxxxxxxx)两种格式,兼容大小写:
第一种:
/** * 全国组织机构代码校验函数 * @param {string} code - 组织机构代码(支持 xxxxxxxx-X / xxxxxxxxx 格式) * @return {boolean} true=合法,false=非法 */ function checkOrgCode(code) { // 1. 空值校验 if (!code) return false; // 2. 统一转为大写,去除横杠(兼容两种格式) const upperCode = code.toUpperCase().replace(/-/g, ''); // 必须是9位 数字/大写字母 const reg = /^[0-9A-Z]{9}$/; if (!reg.test(upperCode)) return false; // 3. 定义加权因子 + 字符集(0-9,A-Z对应的值) const weight = [3, 7, 9, 10, 5, 8, 4, 2]; // 8位加权因子 const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // 4. 拆分:前8位本体码,第9位校验码 const body = upperCode.substring(0, 8); // 本体码 const checkCode = upperCode.substring(8, 9); // 输入的校验码 // 5. 计算求和 let sum = 0; for (let i = 0; i < 8; i++) { // 获取字符对应的值 × 加权因子 sum += chars.indexOf(body[i]) * weight[i]; } // 6. 计算标准校验码 let c9 = 11 - (sum % 11); // 处理特殊规则 if (c9 === 10) c9 = 'X'; if (c9 === 11) c9 = '0'; // 7. 最终校验:计算值 == 输入值 return c9.toString() === checkCode; }仅支持带横杠格式
function checkOrgCodeSimple(code) { if(!code) return false; const reg = /^[0-9A-Z]{8}-[0-9X]$/i; if(!reg.test(code)) return false; const [body, check] = code.toUpperCase().split('-'); const weight = [3,7,9,10,5,8,4,2]; const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; let sum = 0; for(let i=0;i<8;i++) sum += chars.indexOf(body[i]) * weight[i]; let c9 = 11 - sum%11; c9 = c9===10?'X':c9===11?'0':c9+''; return c9 === check; }测试用例
// 测试合法代码 console.log(checkOrgCode('51100000-2')); // true console.log(checkOrgCode('511000002')); // true(无横杠) console.log(checkOrgCode('D1234567-X')); // true // 测试非法代码 console.log(checkOrgCode('51100000-3')); // false console.log(checkOrgCode('12345678')); // false(长度不足) console.log(checkOrgCode('123456789-0')); // false(格式错误)