为什么含加减号或e的type=number输入框会返回空值?
问题根本原因
浏览器对type="number"的输入框有原生的规范约束:根据HTML标准,当输入内容不符合合法数字格式时,输入框的value属性会返回空字符串。
- 合法的数字格式包括:正负号开头的整数/小数、科学计数法格式(如
-55、+12.3、2e4),这类输入可以正常拿到value值 - 不符合数字格式的输入(如
321-51、+e-)会被浏览器判定为无效值,value直接返回空,你的校验逻辑是基于value的内容判断,空字符串里自然找不到e、-等字符,所以校验完全失效。
可行解决方案
方案1:从输入侧直接拦截非法字符(推荐)
直接禁止用户输入+、-、e这类你不需要的字符,从源头避免无效输入:
const numInput = document.querySelector(".forge-points-input") // 拦截键盘输入 numInput.addEventListener('keydown', e => { if(['e', 'E', '+', '-'].includes(e.key)) { e.preventDefault() } }) // 拦截粘贴带非法字符的内容 numInput.addEventListener('paste', e => { const pasteContent = e.clipboardData.getData('text') if(/[eE+-]/.test(pasteContent)) { e.preventDefault() } })
方案2:更换输入框类型保证能拿到全量输入
如果需要灵活做自定义校验,可以把type="number"换成type="text"搭配inputmode="numeric",既可以唤起移动端数字键盘,又能保证value永远返回用户输入的所有内容,再做校验就不会有问题:
<input type="text" inputmode="numeric" class="forge-points-input" id="forge-points-input"> <button type="button" id="forge-points-btn">Count</button>
校验逻辑可以简化为正则判断:
const countBtn = document.getElementById("forge-points-btn"); function quantityHandler() { const userInput = document.querySelector(".forge-points-input").value.trim(); // 包含非法字符直接返回 if(/[eE+-]/.test(userInput)) return; // 可选:额外加纯数字校验 if(!/^\d*$/.test(userInput)) return; // 其余业务代码 }
内容的提问来源于stack exchange,提问作者Abgar
相关产品推荐
相关产品推荐

