前言
el-input限制其输入的格式,采用正则表达式以及控件的input方法进行监听。以下则是常用的监听格式。
<el-input v-model="input" @input="watchInput" />
一、只允许输入数字(最多为2位小数)
watchInput(val) {;
this.input =
this.input
.replace(/[^\-\d.]/g, "") //只能输入 数字 小数点 -
.replace(/(?!^)-/g, "") // 只能出现一次-
.replace(/^0+(\d)/, "$1") //如果第一位是 0 就替换成后面的数字
.replace(/^\./, "0.") //如果第一位是 . 就 替换成 0.
.match(/^[\d\-]*(\.?\d{0,2})/g)[0] || ""; //开头只能允许数字或者 -
}
二、只允许输入数字(不限制小数位数)
watchInput(val) {;
this.input =
this.input
.replace(/[^\-\d.]/g, "") //只能输入 数字 小数点 -
.replace(/(?!^)-/g, "") // 只能出现一次-
.replace(/^0+(\d)/, "$1") //如果第一位是 0 就替换成后面的数字
.replace(/^\./, "0.") //如果第一位是 . 就 替换成 0.
.match(/^[\d\-]*(\.?\d{0,})/g)[0] || ""; //开头只能允许数字或者 -
}
三、只允许输入正整数
watchInput(val) {
this.input =
this.input.replace(/[^\d]/g, "")
.replace(/^0+(\d)/, "$1"); //如果第一位是 0 就替换成后面的数字
}