利用input方法限制输入框只能输入限制范围内的数字
1 2 3
| <el-input v-model="abc" @input="abc=abc.replace(/\D/g,'')"></el-input>
|
1 2 3 4 5
| <el-input v-model="minProportionValue" @input="minProportionValue = formatTwoDecimal(minProportionValue, 100)" > </el-input>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
formatTwoDecimal(value, maxNumber, isIncludeMax) { value = value.replace(/[^\d.]/g, ''); value = value.replace(/^\./g, ''); value = value.replace(/\.{2,}/g, "."); value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); if (value.indexOf('.') < 0 && value != '') { value = parseInt(value); } if (maxNumber) { const bool = isIncludeMax ? +value >= maxNumber : +value > maxNumber; if (bool) { let valueString = String(value) value = valueString.slice(0, valueString.length - 1) } } return value }
|
方法1:在每次输入发生变化时,使用正则表达式来验证输入内容是否符合要求。如果不符合,就将输入框的值恢复为上一次符合要求的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <!DOCTYPE html> <html> <head> <meta charset="UTF - 8"> <title>限制输入数字和小数位数</title> </head>
<body> <input type="text" id="inputBox"> <script> const inputBox = document.getElementById('inputBox'); let lastValidValue = ''; inputBox.addEventListener('input', function () { const value = this.value; const regex = /^\d*(\.\d{0,4})?$/; if (regex.test(value)) { lastValidValue = value; } else { this.value = lastValidValue; } }); </script> </body>
</html>
|
方法2:使用replace方法替换输入内容
该方法和上述限制两位小数的方法类似,具体不同的地方为限制小数位数的方式
1 2 3 4 5 6 7 8 9 10 11 12
| numberInput.addEventListener('input', function () { this.value = this.value.replace(/[^\d.]/g, ''); this.value = this.value.replace(/^\./g, ''); this.value = this.value.replace(/\.{2,}/g, '.'); this.value = this.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); if (this.value.split('.').length > 1) { this.value = this.value.split('.')[0] + '.' + this.value.split('.')[1].substring(0, 4); } });
|
遇到了@input=”data.inputValue.replace(/[^a-zA-Z0-9]/g, ‘’)”不生效的情况,可采用如下写法
1 2 3 4 5 6
| <a-input :value="data.inputValue" @input="inputChange" :maxlength="20"></a-input> const inputChange = e => { const value = e.target.value.replace(/[^a-zA-Z0-9]/g, ''); data.inputValue = value; e.target.value = value; // 强制更新输入框的值 };
|