项目要求输入框只能输入数字和一个小数点,长度最多16位,小数点保留两位小数
<input
type="number"
@keyup="proving(index)"
v-model="item.value"
placeholder="请输入"
/>
proving(index){
// this.list[index].value 是输入框输入的值,这里是列表循环出来的输入框
// 先把非数字的都替换掉,除了数字和.
this.list[index].value = this.list[index].value.replace(/[^\d.]/g, '');
// 必须保证第一个为数字而不是.
this.list[index].value = this.list[index].value.replace(/^\./g, '');
// 保证只有出现一个.而没有多个.
this.list[index].value = this.list[index].value.replace(/\.{2,}/g, '');
// 保证.只出现一次,而不能出现两次以上
this.list[index].value = this.list[index].value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
let count = -1
for (let i in this.list[index].value) {
if (this.list[index].value[i] === '.') {
count = i
}
if (count !== -1) {
if (i - count > 2) {
this.list[index].value = this.list[index].value.substring(0, this.list[index].value.length - 1)
}
}
}
// 限制输入长度最多为16位
if(this.list[index].value.length > 16){
this.list[index].value = this.list[index].value.slice(0, 16)
}
}