输入框只能输入数字遇到的坑 只能输入数字、小数及负数

输入框只能输入非负整数,数字首位不能一个或者多个0,单个0除外

方案一:

// 对应数值输入时校验
onInput() {
    // 清空数字以外的字符
    this.value = this.value.replace(/\D/g, '')
    // 转成数字
    this.value = Number(this.value)
}

方案二:

// 对应数值输入时校验
onInput() {
    // 清空数字以外的字符
    this.value = this.value.replace(/\D/g, '')
    // 清除数字前面的0,只有一位0除外
    this.value = this.value.replace(/0*(\d+)/,'$1')
}

输入框只能输入非负数,可以是小数,数字首位不能一个或者多个0,单个0除外

      this.costPrice = this.costPrice.replace(/[^\d.]/g, '');
      //必须保证第一个为数字而不是.
      this.costPrice = this.costPrice.replace(/^\./g, '');
      //保证只有出现一个.而没有多个.
      this.form.costPrice = this.costPrice.replace(/\.{2,}/g, '.');
      //保证.只出现一次,而不能出现两次以上
      this.costPrice = this.costPrice.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
      // 清除数字前面的0,只有一位0除外
      this.costPrice = this.costPrice.replace(/0*(\d+)/, '$1');

不知道,还有没有简便的方法。我现在用这个好像还行

猜你喜欢

转载自blog.csdn.net/m0_53942074/article/details/137587293