如何保证移动端vue只能输入金额?

如何保证移动端的vue项目,在input中只能输入金额?包括数字和小数点。 发现如果调type=‘tel’的话只有数字没有小数点,调type=‘number’还有其他符号。 监听input动作来去掉符号发现也不行,不知道是不是自己代码的问题。

  <input ref="content" type="number" pattern="[0-9]{,6}" @input="handleAmountChange"  v-model.number.trim="money"  />
    handleAmountChange(e) {
      this.money = e.target.value.replace(/[^\d]/g, '')
      // 必须保证第一个为数字而不是.
      this.money = this.money.replace(/^\./g, '0.')
      // 保证只有出现一个.而没有多个.
      this.money = this.money.replace(/\.{2,}/g, '.')
      // 保证.只出现一次,而不能出现两次以上
      this.money = this.money
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      // 只能输入两个小数
      this.money = this.money.replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3')
    },
阅读 5.3k
2 个回答
methods:{
    onMoneyBlur(){
        if(!/^[0-9]+(\.?(?=[0-9])[0-9]{0,2})?$/.test(this.money)){
            this.money = 0;
            return;
        }
    }
}
针对.开头的传字符串测试为false: xx.test('.1')

数字则为 true 应该是 js 自动转换了: xx.test(.1)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题