vue项目原生input框限制只能输入金额

前言

使用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;
    },


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值