(原创)实用的输入框即时校验

下面2段代码可以快速生成一个即时校验的input文本框,在页面很多地方都可以使用

 

代码
<!-- 只允许输入正整数,如1234,常用于数量 -->
<input onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,'').replace(/^0\d{0,4}$/g,''));"
onkeyup
="this.value=this.value.replace(/[^\d]/g,'').replace(/^0\d{0,4}$/g,'');" />
<!--只允许输入正数,如12.34,常用于金额-->
<input onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1'));"
onkeyup
="this.value=this.value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1');" />

 
<!-- 或者如下直接定义一个函数,在需要使用的地方调用一下即可 -->
<script>
//只能输入整数
function onlyInteger(obj) {
 
var curVal=obj.value;
 
if((curVal+'').length > 1) {
  obj.value 
= obj.value.replace(/[^\d]/g,'').replace(/^0\d{0,4}$/g,'');
 } 
else {
  obj.value 
= obj.value.replace(/\D/g,'');
 }
}
</script>
<input onkeyup="onlyInteger(this)" />

 

 

posted @ 2010-09-21 15:36  arix04  阅读(335)  评论(0编辑  收藏  举报