如何用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'); }); } });
修改说明:
- 排除当前输入框:使用
.not($currentInput)跳过当前正在编辑的输入框,避免和自身匹配 - 修正DOM定位:直接通过当前输入框的
siblings找到错误提示框,避免$(this)指向错误的问题 - 空值处理:空输入不执行验证逻辑,减少无效检查
- 统一字符串处理:用
$.trim()去除前后空格,避免因空格导致的误判 - 修正提示框name:匹配你HTML里的
tel-num-error-msg
内容的提问来源于stack exchange,提问作者murday1983
相关产品推荐
相关产品推荐

