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

如何用jQuery验证表格中输入的电话号码不重复?

解决多行电话号码重复验证问题

你的代码存在几个关键问题导致误判重复:

  • 收集号码时包含了当前输入框自身的值,导致必然匹配到"重复"
  • $.each遍历数组时$(this)指向的是数组元素而非DOM节点,无法正确定位错误提示框
  • 错误提示框的name属性拼写错误(代码里用了assoc-num-error-msg,但实际是tel-num-error-msg)
  • 不必要的rowCount>1限制,单行时也应该允许验证逻辑运行

以下是修正后的代码:

$(document).on('focusout', 'input[name="Associated Numbers"]', function() {
    const $currentInput = $(this);
    const enteredNum = $.trim($currentInput.val());
    const $errorMsg = $currentInput.siblings('div[name="tel-num-error-msg"]');
    
    // 先隐藏之前的错误提示
    $errorMsg.hide();

    if (!enteredNum) return; // 空值不验证

    let isDuplicate = false;

    // 遍历所有号码输入框,排除当前输入框
    $('input[name="Associated Numbers"]').not($currentInput).each(function() {
        const existingNum = $.trim($(this).val());
        if (existingNum === enteredNum) {
            isDuplicate = true;
            return false; // 找到重复就停止遍历
        }
    });

    if (isDuplicate) {
        $errorMsg.text('Number has already been added').show(0, function() {
            $currentInput.trigger('focus');
        });
    }
});

修改说明:

  1. 排除当前输入框:使用.not($currentInput)跳过当前正在编辑的输入框,避免和自身匹配
  2. 修正DOM定位:直接通过当前输入框的siblings找到错误提示框,避免$(this)指向错误的问题
  3. 空值处理:空输入不执行验证逻辑,减少无效检查
  4. 统一字符串处理:用$.trim()去除前后空格,避免因空格导致的误判
  5. 修正提示框name:匹配你HTML里的tel-num-error-msg

内容的提问来源于stack exchange,提问作者murday1983

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 18:35:02