一、input
只能輸入框只能輸入正整數,輸入同時禁止了以0開始的數字輸入,防止被轉化為其他進制的數值。
<!-- 不能輸入零時-->
<input type='text' οninput="value=value.replace(/^(0+)|[^\d]+/g,'')"><!-- 能輸入零時-->
<input type='text' οninput="value=value.replace(/^0+(\d)|[^\d]+/g,'')">
附:只能輸入中文:
<input type="text" οninput="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')">
附:只能輸入英文:
<input type="text" οninput="this.value=this.value.replace(/[^a-zA-Z]/g,'')">
二、el-input
<el-input size="small"οnkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"v-model="count"maxlength="9"></el-input>
data() {return {count: 0}
}
el-input輸入金額,保留兩位小數
需求:“只允許輸入金額保留兩位小數”,有2種實現方法
方法一(通過正則控制):
<el-inputv-model="inputTable.amount"@input="formatNum(form.amount, 'amount')"
></el-input>
formatNum(val, key) {let temp = val.toString();temp = temp.replace(/。/g, ".");temp = temp.replace(/[^\d.]/g, ""); //清除"數字"和"."以外的字符temp = temp.replace(/^\./g, ""); //驗證第一個字符是數字temp = temp.replace(/\.{2,}/g, ""); //只保留第一個, 清除多余的temp = temp.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");temp = temp.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能輸入兩個小數this.form[key] = temp;
},
方法二(使用組件):
這個是我最近才發現的,方便多了TT
設置精度precision,即可四舍五入;
再改改樣式,隱藏按鈕,靠左對齊,最后效果和普通的input無異
<el-input-number v-model="num" :precision="2"></el-input-number>