正则表达式限制input输入——小数点后保留两位小数

html

<div><input type="text" v-model="newPrice" /></div>

js

data() {
    return { newPrice: "",  timer: null };
},
watch: {
    newPrice(val){
        clearTimeout(this.timer); //防抖
        this.timer = setTimeout(() => {
              /**
              *小数点不好控制,把控不了用户输入后是否继续输入,
              *所以如果输入后1秒内没有再输入则小数点就会被清掉
              */
              let reg = /^(0|[1-9]\d*)(\.\d{1,2})?/;
              let price = val.match(reg);
              this.newPrice = price ? price[0] : '';
         }, 1000);
    }
}
实例

index.vue

<template>
  <div>
    <el-input
      v-model="inputValue"
      @input="handleInput"
    ></el-input>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    };
  },
  methods: {
    handleInput() {
      // 判断输入是否为数字且最多两位小数
      const reg = /^\d+(\.\d{1,2})?$/;
      if (reg.test(this.inputValue)) {
        // 如果输入为一位小数,则补0凑成两位小数
        if (this.inputValue.includes('.') && this.inputValue.split('.')[1].length === 1) {
          this.inputValue = parseFloat(this.inputValue).toFixed(2);
        }
      } else {
        // 输入不符合要求,清空输入框
        this.inputValue = '';
      }
    }
  }
};
</script>

更多推荐