如何限制用户输入的数字不超过8位?
问题原因
- 原代码使用
isNaN判断非数字存在逻辑漏洞:空字符串、空格、科学计数法格式字符的判断结果不符合预期,无法准确识别所有非数字输入 - 仅删除单次输入的末尾字符,无法覆盖粘贴、拖拽等批量输入非数字内容的场景
- 动态修改输入框
type属性容易触发浏览器兼容性问题,type="number"的输入框在部分场景下读取value长度会出现异常
可行实现方案
建议直接通过正则替换所有非数字字符后截断长度,逻辑更简单稳定,可覆盖所有输入场景:
原生JavaScript实现
HTML 部分:
<!-- 用inputmode="numeric"可触发移动端数字键盘,避免number类型的多余加减按钮 --> <input type="text" inputmode="numeric" id="numInput" placeholder="请输入8位数字">
JS 逻辑:
const numInput = document.getElementById('numInput') // 监听input事件覆盖所有输入、粘贴、拖拽场景 numInput.addEventListener('input', (e) => { // 替换所有非数字字符后截断前8位 e.target.value = e.target.value.replace(/[^0-9]/g, '').slice(0, 8) })
Vue3 实现示例
<template> <input type="text" inputmode="numeric" v-model="inputVal" @input="handleInput" placeholder="请输入8位数字" > </template> <script setup> import { ref } from 'vue' const inputVal = ref('') const handleInput = (e) => { inputVal.value = e.target.value.replace(/[^0-9]/g, '').slice(0, 8) } </script>
React 实现示例
import { useState } from 'react' function NumInput() { const [inputVal, setInputVal] = useState('') const handleInput = (e) => { const val = e.target.value.replace(/[^0-9]/g, '').slice(0, 8) setInputVal(val) } return ( <input type="text" inputmode="numeric" value={inputVal} onInput={handleInput} placeholder="请输入8位数字" /> ) }
内容的提问来源于stack exchange,提问作者Aegon
相关产品推荐
相关产品推荐

