You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一HTML页面中使用JS验证两个不同的TR ID号码

TC身份证号双输入框校验修复方案

存在的问题

  • 现有代码仅为新娘身份证输入框#id_identity_bride绑定了校验事件,未覆盖新郎输入框#id_identity_groom
  • 原有校验函数存在逻辑错误,无法正确识别合法的TC身份证号:
    • 重复声明toplamY变量
    • 第10位校验位的计算规则错误,且字符截取方法使用错误,无法正确匹配校验位

修复后完整代码

原有HTML代码无需修改,将JS代码替换为以下内容即可:

/* TC Kimlik 校验函数 */
var TCKimlikKontrol = function(deger) {
    deger = deger.toString();
    // 校验规则1:11位数字,首位不能为0
    var formatKural = /^[1-9][0-9]{10}$/.test(deger);
    if (!formatKural) return false;

    var tekBasamakToplam = 0, ciftBasamakToplam = 0, tumToplam = 0;
    // 计算1、3、5、7、9位的和
    for (var i = 0; i < 9; i += 2) {
        tekBasamakToplam += Number(deger.charAt(i));
    }
    // 计算2、4、6、8位的和
    for (var i = 1; i < 8; i += 2) {
        ciftBasamakToplam += Number(deger.charAt(i));
    }
    // 校验规则2:(奇数位和*7 - 偶数位和) 模10等于第10位
    var onuncuBasamakKural = ((tekBasamakToplam * 7) - ciftBasamakToplam) % 10 == Number(deger.charAt(9));
    // 校验规则3:前10位总和模10等于第11位
    for (var i = 0; i < 10; i++) {
        tumToplam += Number(deger.charAt(i));
    }
    var onbirinciBasamakKural = tumToplam % 10 == Number(deger.charAt(10));

    return onuncuBasamakKural && onbirinciBasamakKural;
};

// 同时选中两个身份证输入框
const tcInputlari = document.querySelectorAll("#id_identity_bride, #id_identity_groom");
const sonucAlani = document.querySelector("#sonuc");

// 给两个输入框批量绑定校验事件
tcInputlari.forEach(input => {
    input.oninput = function() {
        if (this.value.length < 11) {
            sonucAlani.textContent = "请输入完整的11位TC身份证号";
            return;
        }
        if (TCKimlikKontrol(this.value)) {
            sonucAlani.textContent = "TC身份证号有效,谢谢。";
        } else {
            sonucAlani.textContent = "请输入有效的TC身份证号。";
        }
    }
});

改动说明

  • 修正了校验函数逻辑,完全符合土耳其TC身份证号的官方校验规则
  • 同时为两个输入框绑定校验事件,任意输入框输入内容都会触发校验
  • 增加输入长度判断,输入不足11位时不会直接报错,优化使用体验

内容的提问来源于stack exchange,提问作者Uğur TÜRK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:36:02