价格金额输入控制

最近做的小程序项目里,需要根据用户实时输入来计算优惠价,这就需要控制用户输入的只能是金额,首先需要规定input的type:

然后在js相应的方法里使用控制输入只能是金额的公共方法:

bindMoneyInput(e) {
    const moneyVal =  publicMoneyInput(e)
}

公共方法:

export const publicMoneyInput = (e) => {

  let moneyVal = e.detail.value;

  let str = moneyVal.split(".")

  // 控制不能输入两个小数点

  if (str.length - 1 > 1) {
    if (moneyVal == '0..') {
      moneyVal = '0.'
    }
    moneyVal = moneyVal
  }

  // 控制不能输入00.xx

  if (str[0].length > 1) {
    if (str[0].indexOf(0) == '0') {
      // console.log('数字格式不正确!');
      moneyVal = '';
    }
  }

  if (moneyVal == '.') {
    moneyVal = moneyVal.replace(/[.]/g, '0.')
  }

  if (str[1]) {
    if (str[1].length <= 2) {
      moneyVal = str[0] + '.' + str[1]
    } else {
      moneyVal = str[0] + '.' + str[1].slice(0, 2)
    }
  }

  return moneyVal

}

你可能感兴趣的:(价格金额输入控制)