onkeypress 键盘按下事件
οnkeyup 键盘弹起事件
onpaste 粘贴事件
onblur 焦点离开input输入框时
直接写在input上:
<input onkeypress="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
οnkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
onblur="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}">
封装成js函数:
<input onkeypress="validataInt(this)" οnkeyup="validataInt(this)" onblur="validataInt(this)"><script>
function validataInt(ob) {if(ob.value.length==1){ob.value=ob.value.replace(/[^1-9]/g,'')}else{ob.value=ob.value.replace(/\D/g,'')}
}
</script>
限制类型:
- 正整数
if(ob.value.length==1){ob.value=ob.value.replace(/[^1-9]/g,'')}
else{ob.value=ob.value.replace(/\D/g,'')}
- 浮点数(包含负数)
ob.value=ob.value.replace(/[^\-?\d.]/g,'')
- 数字+两位小数
ob.value = ob.value.replace(/[^\d.]/g,"");//清除"数字"和"."以外的字符
ob.value = ob.value.replace(/^\./g,""); //验证第一个字符是数字
ob.value = ob.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
ob.value = ob.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
ob.value = ob.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
- 不允许输入汉字
ob.value=ob.value.replace(/[\u4e00-\u9fa5]/ig,'')