Bootstrap-Vue数值输入框在安卓Chrome 90允许输入逗号点号问题咨询
安卓端Chrome数字输入框异常问题排查与解决
问题复现前提
该问题仅在安卓端Google Chrome(版本90.0.4430.210)上复现,其他浏览器均不存在此问题。
原有实现代码
输入框模板
<b-form-input v-model="manualInput" class="text-center text-primary bold font-weight-bold" id="manInput" type="number" inputMode="numeric" pattern="[0-9]*" min="1" max="20" @keypress="checkValidation($event)" @keyup="checkValidation($event)" @mouseup="checkValidation($event)" @paste="onPaste($event)" />
注:onPaste事件仅用于禁止用户粘贴内容,不涉及其他核心逻辑。
输入校验逻辑
private checkValidation(evt) { console.log(this.manualInput); // 校验是否有输入内容 if (this.manualInput.length) { // 转数字格式 var stamps: number = +this.manualInput; // 校验输入值是否合法 if (stamps < this.min || stamps > this.max || !this.manualInput.match("[0-9]{1,3}")) { this.showAlert = true; this.isValid = false; } else { this.showAlert = false; this.isValid = true; } } else { // 无输入内容 this.showAlert = false; this.isValid = false; } }
异常表现
- 原有逻辑在桌面端全浏览器、移动端Firefox、移动端Safari运行正常,仅安卓端Chrome允许用户输入逗号、点号
- 新增过滤代码
this.manualInput.replace(".", "").replace(",", "")后仍存在异常:仅输入逗号时,获取到的输入值为空字符串,控制台打印结果也为空;只有后续输入数字后,之前输入的逗号才会出现在打印的字符串中,误导用户认为符号输入合法,使用体验差
问题成因
该问题是安卓端Chrome对type="number"输入框的特殊处理逻辑导致的兼容性问题:
- 安卓Chrome的数字软键盘为了适配不同地区的数字格式习惯,默认允许输入小数点、逗号作为小数/千位分隔符;且当输入内容不符合标准数字格式时,浏览器不会将当前输入内容同步给输入框的
value属性,这就是单独输入逗号时拿到空值的原因,等后续输入数字后整体符合数字格式,才会把完整内容同步给绑定的v-model变量,出现值滞后的现象。 type="number"输入框的原生处理逻辑优先级高于你绑定的keypress/keyup事件,事件触发时浏览器可能还未完成输入值的同步,导致你写的过滤逻辑无法生效。
解决方案
- 首先将输入框的
type属性从number改为text,保留inputMode="numeric"和pattern="[0-9]*",这两个属性依然可以唤起移动端的数字软键盘,同时不会触发Chrome针对数字输入框的特殊处理,所有输入内容都会实时同步给v-model,不会出现值滞后问题。 - 调整校验逻辑,先过滤所有非数字字符再做后续校验,参考修改后的代码:
private checkValidation(evt) { // 先过滤所有非数字字符,直接更新绑定值 this.manualInput = this.manualInput.replace(/[^0-9]/g, '') console.log(this.manualInput); // 原有校验逻辑保留 if (this.manualInput.length) { const stamps = Number(this.manualInput); if (stamps < this.min || stamps > this.max) { this.showAlert = true; this.isValid = false; } else { this.showAlert = false; this.isValid = true; } } else { this.showAlert = false; this.isValid = false; } }
- 额外给输入框绑定
@input="checkValidation($event)",覆盖所有输入触发场景,避免遗漏自动填充、手写输入等场景的变更。
内容的提问来源于stack exchange,提问作者Zumpel
相关产品推荐
相关产品推荐

