js正则限制input只能输入金额

限制input只能输入金额

JS代码:

function checkInput(_this) {
  if (_this.value != '' && _this.value.substr(0, 1) == '.') {
    _this.value = '0.00'
  }
  if (_this.value == '') {
    _this.value = '0.00'
  }
  _this.value = _this.value.replace(/^0*(0\.|[1-9])/, '$1') // 禁止粘贴
  _this.value = _this.value.replace(/[^\d.]/g, '0.00') // 禁止输入非数字
  _this.value = _this.value.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
  _this.value = _this.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
  _this.value = _this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数

  if (_this.value.indexOf('.') < 0 && _this.value != '') {
    // 以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
    if (_this.value.substr(0, 1) == '0' && _this.value.length == 2) {
      _this.value = _this.value.substr(1, _this.value.length)
    }
  }
  if (!_this.value) {
    _this.value = 0.0
  }
}

function checkNum(_this){
  // 失去焦点的时候判断 如果最后一位是 . 末尾补0
  _this.value.endsWith('.') ? _this.value += '0' : _this.value
}

HTML示例代码:

<input type="text" class="moneys" value="" onkeyup="checkInput(this)" onblur="checkNum(this)" />
发布了8 篇原创文章 · 获赞 27 · 访问量 2095

猜你喜欢

转载自blog.csdn.net/weixin_45612438/article/details/105358120