只能输入数字类型
提示:使用正则过滤输入值
方法一
输入不符合字符后,不清空原来数字
<template>
<el-input
v-model.number="nCapacity"
onkeyup="value=value.replace(/^\.+|[^\d.]/g,'')"
@input="fnShareCapacityInput">
</el-input>
</template>
<script>
export default {
data() {
return {
nCapacity: 0
}
},
fnShareCapacityInput() {
// 增加限制
if (event.target.value === '') {
this.nCapacity = 0;
} else if (event.target.value > 5000) {
this.nCapacity = 5000;
} else if (event.target.value < 1) {
this.nCapacity = 0;
}
}
}
</script>
方法二
输入不符合字符后,清空原来数字
<template>
<el-input
v-model="num"
oninput="if(value === ''){value = 0} if (isNaN(value)) {value = null}if (value.indexOf('.') > 0) {value = value.slice(0, value.indexOf('.'))} if(value > 1000000) value = 1000000"
maxLength="1000000"
></el-input>
</template>
只能输入数字类型,包括小数点、负数
提示:限制奇怪的输入:
<template>
<el-input
v-model="nZoomInput"
@input="fnZoomInputBox"
>
</el-input>
</template>
<script>
export default {
data() {
return {
nZoomInput: 1
}
},
methods: {
// 输入框修改 缩放
fnZoomInputBox(val) {
let str = val.charAt(0), sInput;
sInput = val.replace(/[^0-9.]/g, "");
if (str === "-") sInput = "-" + sInput;
sInput = this.fnRegUnified(sInput);
if (sInput === "" || sInput < 0) {
sInput = 0;
} else if (sInput > 8) {
sInput = 8;
}
this.nZoomInput = sInput;
},
// 统一正则判断
fnRegUnified(val) {
val = val.replace(/^00/, "0."); //开头不能有两个0
val = val.replace(/^\./g, "0."); //开头为小数点转换为0.
val = val.replace(/\.{2,}/g, "."); //两个以上的小数点转换成一个
val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); //只保留一个小数点
val = val.replace(new RegExp("^(\\d+)\\.(\\d{2}).*$"), "$1.$2"); // 保留小数点后两位数
return val;
},
}
}
</script>