如何使用原生JavaScript实现指定格式的硬件ID输入框校验功能
硬件ID输入校验实现方案
原有代码失效原因
- 无参校验函数中仅获取了输入框DOM对象,未读取实际输入的文本值,导致长度、字符校验全部失效
- 缺少依赖的
isStringLimitedToHex工具函数定义,函数执行时会抛出未定义错误 - 事件绑定选型不合理:
onchange仅在输入框失焦时触发,onkeydown触发时输入的最新值还未写入输入框,无法拿到当前输入的完整值 - 传参方式错误:绑定事件时直接写
isHardwareIDValid(hid)中的hid未定义,无法正确传递输入值
完整实现代码
1. 输入框代码(添加实时校验触发)
<input type="text" class="extrainfofield" id="ORDERPARAMETERS" name="ORDERPARAMETERS" value="##$LBL_HARDWAREID##" size="39" placeholder="Enter Hardware ID" oninput="checkHardwareID()"> <span id="hidErrorTip" style="color:red;display:none;margin-left:10px">硬件ID格式错误,请输入类似1050-5562-31AB-ABCD-123E-25DA-1A35-FADC格式的ID</span>
2. 原生JavaScript校验代码
// 十六进制字符校验工具函数 function isStringLimitedToHex(str) { return /^[0-9A-Fa-f]+$/.test(str); } // 硬件ID格式校验函数 function isHardwareIDValid(hid) { // 此处用正则简化校验逻辑,也可保留原有逐段校验写法,二选一即可 const reg = /^[0-9A-Fa-f]{4}(-[0-9A-Fa-f]{4}){7}$/; return reg.test(hid) && hid !== "0000-0000-0000-0000-0000-0000-0000-0000"; } // 校验触发与反馈函数 function checkHardwareID() { const hidInput = document.getElementById("ORDERPARAMETERS"); const errorTip = document.getElementById("hidErrorTip"); const hidValue = hidInput.value.trim(); // 为空时不显示错误 if (hidValue === "") { errorTip.style.display = "none"; hidInput.removeAttribute("data-invalid"); return true; } // 校验不通过显示错误 if (!isHardwareIDValid(hidValue)) { errorTip.style.display = "inline"; hidInput.setAttribute("data-invalid", "1"); return false; } // 校验通过隐藏错误 errorTip.style.display = "none"; hidInput.removeAttribute("data-invalid"); return true; } // 可选:表单提交时拦截校验,避免非法值提交 document.querySelector("form").addEventListener("submit", function(e) { if (!checkHardwareID()) { e.preventDefault(); alert("请输入正确格式的硬件ID"); } });
扩展优化(可选)
如果需要用户输入时自动补全横杠,提升使用体验,可以替换校验逻辑,自动格式化输入内容:
function checkHardwareID() { const hidInput = document.getElementById("ORDERPARAMETERS"); const errorTip = document.getElementById("hidErrorTip"); // 过滤非法字符,统一转为大写 let hidValue = hidInput.value.toUpperCase().replace(/[^0-9A-F]/g, ''); // 自动插入横杠 let formattedValue = ''; for (let i = 0; i < hidValue.length; i++) { if (i > 0 && i % 4 === 0) { formattedValue += '-'; } formattedValue += hidValue[i]; } // 限制最大长度为39位 formattedValue = formattedValue.slice(0, 39); hidInput.value = formattedValue; // 后续校验逻辑不变 if (formattedValue === "") { errorTip.style.display = "none"; hidInput.removeAttribute("data-invalid"); return true; } if (!isHardwareIDValid(formattedValue)) { errorTip.style.display = "inline"; hidInput.setAttribute("data-invalid", "1"); return false; } errorTip.style.display = "none"; hidInput.removeAttribute("data-invalid"); return true; }
内容的提问来源于stack exchange,提问作者Jeff Berlin
相关产品推荐
相关产品推荐

