正则校验:只能输入数字和小数点,且保留两位小数

2,427 阅读1分钟

最近遇到一个需求,修改订单金额,文本框仅显示最多两位小数输入更多则不支持继续输入。 进行2步骤操作, 第一步、在输入时限制输入的类型及输入的小数点后的长度

                     <el-input
                      v-model="locationVal"
                      placeholder="请输入内容"
                      style="width:100px"
                      size="small"
                      @input="onInput()"
                      @blur="onInputDone()"
                      maxlength='10'
                    ></el-input>

输入的正则校验

  onInput(){
      this.locationVal = this.locationVal.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
      this.locationVal =this.locationVal.replace(/^\./g, '0.'); //首位不能输入“.”
      this.locationVal =this.locationVal.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
      this.locationVal = this.locationVal.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
      this.locationVal = this.locationVal.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数  
    },

失去焦点的正则校验

onInputDone(){
      if(this.locationVal===''){
         this.$message({ message: "请输入订单实付金额", type: "error" });
        return
      }
      if(this.locationVal>100000){
        this.$message({ message: "订单实付金额不能大于100000", type: "error" });
        return
      }
      if(  this.locationVal !=""){//如果没有小数点,首位不能为0,如01、02...
            this.locationVal = parseFloat(this.locationVal);
      }
      this.locationVal =  this.returnFloat(this.locationVal)
      //把金额传给后端
      let params = {
        shopNick:this.formInline.shopNick,
        tid:this.subOrders.tid,
        orderPayment:this.locationVal
      }
       this.$api.orderInquiry.EditOrderAmount(params).then((res) => {
        console.log(res.result);
        if(res && res.code==200 && res.result){
          this.isLocationVal = false;
          this.subOrders.payment = this.locationVal;
           this.$message({ message: "修改成功", type: "success" });
        }
      });
    },
    //把不符合2位小数的数字进行处理
     returnFloat(value){
        let s=value.toString().split(".");
        if(s.length==1){
          value=value.toString()+".00";
          return value;
        }
        if(s.length>1){
          if(s[1].length<2){
            value=value.toString()+"0";
          }
          return value;
        }
    },

**提示:input上加上maxlength='10'是因为当输入金额特别大比如18位数字时,会进行科学计算法的展示,识别不了数字,这样正则校验不通过,因此限制了输入的长度