微信小程序金额输入限制

金额的格式如下:

1、只保留两位小数
2、输入的数字中只能有一个小数点
3、首位不能为0

有两种情况:

1、在input标签上做限制,type属性设置为“digit”,禁止输入其他字符。

<input placeholder="输入金额" value='{{info.money==null?"":info.money}}' type="digit" adjust-position="true" bindblur="inputMoney"></input>

js:

//输入金额
  inputMoney: function(e) {
    console.log(e)
    const exp = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    exp.test(e.detail.value)
    console.log(exp.test(e.detail.value))
    if (!exp.test(e.detail.value)) {
      wx.showModal({
        content: '请输入正确的金额',
        showCancel: true,
      })
    } else {
      this.setData({
        money: e.detail.value
      })
    }
  }

2、输入的时候不做限制,在提交后台时再做一个限制。

/**
 * 金额输入限制
 */
const money = function(param) {
  let num = param.toString(); //先转换成字符串类型
  if (num.indexOf('.') == 0) { //第一位就是 .
    num = '0' + num
  }
  num = num.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
  num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
  num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
  if (num.indexOf(".") < 0 && num != "") {
    num = parseFloat(num);
  }
  return num
}

inputMoney函数:

  inputMoney: function(e) {
    console.log(e)
      this.setData({
        money: config.money(e.detail.value)
      })
  }
发布了102 篇原创文章 · 获赞 26 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/xuelian3015/article/details/103119577
今日推荐