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

Jill ·
更新时间:2024-09-20
· 551 次阅读

限制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示例代码:


作者:Jing.Yao



js正则 输入 js input

需要 登录 后方可回复, 如果你还没有账号请 注册新账号