文本框只能输入数字、字母,屏蔽粘贴

文本框只能输入数字、字母,屏蔽粘贴

 

对文本框进行输入限制,使得文本框只能输入(或不能输入)数字/字母/汉字等等。
操作方法很多,主要用到了正则表达式,onkeyup,onafterpaste。
在需求上可能不止这些情况,或者有交叉需求的情况,可以根据不同条件自行修改语句达到相应的效果,万变不离其宗。


只能输入数字(整数,屏蔽非法粘贴)
<input onkeyup="this.value=this.value.replace(/D/g,'')" onafterpaste="this.value=this.value.replace(/D/g,'')">
只能输入数字(可以有小数点)
<input onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')" />
只能输入数字(整数)
<input onkeyup="JavaScript:this.value=this.value.replace(/D/gi,'')" />
只能输入字母和汉字(屏蔽非法粘贴)
<input onkeyup="value=value.replace(/[d.]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[d.]/g,''))"/>
只能输入字母和数字(屏蔽非法粘贴)
<input onkeyup="value=value.replace(/[W]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[W]/g,''))" />
小数点后只能有最多两位(数字,可以有正负号)
<input onkeyup="if(!/^[+-]*(d)*(.d{0,2})*$/.test(value)) this.value='';" onafterpaste="if(!/^[+-]*(d)*(.d{0,2})*$/.test(value)) this.value='';">
 
不能输入中文
<input onkeyup="value=value.replace(/[u4E00-u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[u4E00-u9FA5]/g,''))" />
不能输入全角标点符(可以有汉字)
<input onkeyup="value=value.replace(/[uFF00-uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[uFF00-uFFFF]/g,''))" />

转自:https://www.cnblogs.com/zhq195/p/4974628.html

原文地址:https://www.cnblogs.com/shiyi2014/p/12461351.html