前言
使用uni-app 调试薪资的输入框遇到既要大于0 还要能以0 开头的问题 记录一下解决方案`
直接是参考别人帖子代码 这里只是做一下记录
感谢原文博主
原文链接:https://blog.csdn.net/TKP666/article/details/128616042
一、废话不多说直接上代码
<template>
<div class="home">
<!-- 必须type设置为text才有效!!!number无效 -->
<input type="text" v-model="amount" @input="limitNum(amount)" />
</div>
</template>
data() {
return {
amount: "",
};
},
//第一种方案:用户输入01、02等,则展示成1、2,等于非小数时过滤第一位0
limitNum(amount) {
amount = amount
.replace(/[^\d.]/g, "") //只能输入数字
.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3") //只能输入两个小数
.replace(/\.{2,}/g, "."); //出现多个点时只保留第一个
// 第一位不让输小数点
if (amount == ".") {
amount = "";
}
// 如果第一位是0,第二位必须大于0或者小数点
if (amount.substring(0, 1) == 0) {
if (amount.substring(1, 2) > 0) {
amount = amount.substring(1, 2);
} else if (
amount.substring(1, 2) === 0 ||
amount.substring(1, 2) === "0"
) {
amount = "0";
}
} else {
// 如果第一位数字大于0(不等于0肯定就大于0),仅需考虑第二位是小数点的情况
if (amount.indexOf(".") !== -1) {
if (amount.substring(0, 1) > 0) {
console.log("第一位大于0");
} else {
console.log("第一位等于0");
if (amount.substring(2, 3) > 0) {
console.log("小数点后第一位大于0");
} else {
console.log("小数点后第一位等于0");
amount = "0.";
}
}
} else {
console.log("没有小数点,正常输入");
}
}
this.amount = amount;
},
//第二种方案:输入00、01等0开头的整数时,直接清空输入框让用户重新输入
num(amount) {
amount = amount
.replace(/[^\d.]/g, "") //只能输入数字
.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3") //只能输入两个小数
.replace(/\.{2,}/g, "."); //出现多个点时只保留第一个
// 第一位不让输小数点
if (amount == ".") {
amount = "";
}
// 如果第一位是0,有第二位且第二位不是小数点的情况下 就清空输入框
if (amount.slice(0, 1) == "0") {
if (amount.slice(1, 2)) {
if (amount.slice(1, 2) == ".") {
console.log("第二位是小数点");
} else {
console.log("第二位不是小数点,清空输入框");
amount = "";
}
}
}
this.amount = amount;
},