欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javascript 基于正则表达式的文本框验证代码

程序员文章站 2022-07-02 19:40:06
1,不能为空

1,不能为空
<input  type="text" onblur="if(this.value.replace(/^ +| +$/g,'')=='')alert('不能为空!')">

2,只能输入英文和数字
<input onblur="if(/[^0-9a-za-z]/g.test(value))alert('有错')">
<input onkeyup="value=value.replace(/[^0-9a-za-z]/g,'')"/>
<input type="text" onkeyup="value=value.replace(/[^\a-\z\a-\z0-9]/g,'')">

3,判断字符由字母和数字,下划线,点号组成.且开头的只能是下划线和字母
/^([a-za-z_]{1})([\w]*)$/g.test(str)

4,只能输入数字
<input name="text" type="text" id="newpage" onkeyup="value=value.replace(/\d/g,'')" onafterpaste="value=value.replace(/\d/g,'')" >

5,只能输入中文
<input type="text" onkeyup="value=value.replace(/[^\u4e00-\u9fa5]/g,'')">

6,只能输入英文
<input type="text" onkeyup="value=value.replace(/[^\a-\z\a-\z]/g,'')">
<input type="text" onkeyup="value=value.replace(/[^a-za-z]/g,'')">

7,只能输入中文、英文、数字、@符号和.符号
<input type="text" onkeyup="value=value.replace(/[^\a-\z\a-\z0-9\u4e00-\u9fa5\@\.]/g,'')">

8,只允许输入英文,且不能粘贴也无法弹出粘贴菜单
<input type="text" onkeyup="value=value.replace(/[^\a-\z\a-\z]/g,'')" onkeydown="fnckeystop(event)" onpaste="return false" oncontextmenu = "return false"/>

只能输入数字和点号(注意:在[^\d\.]里的d不能写成大写d,否则就变成除了数字以外的所有字符)
<input name="price" type="text" size="8" maxlength="8" onkeyup="value=value.replace(/[^\d\.]/g,'')" >

总而言之:先在<input>里输入onkeyup="value=value.replace(/[^\x]/g,'')" 然后在(/[\x]/g,'')里的x换成你想输入的代码就可以了

中文:u4e00-u9fa5
数字:d、0-9
英文:a-z、a-z
其它符号@,点或其它符号.也可以多个,用\隔开就行了.
例如:
中、英文和数字加@符号加点符号:\a-\z\a-\z0-9\u4e00-\u9fa5\@\.

若想在文本框里不能右键弹出菜单和不能粘贴进复制的信息的话就要在<input>里输入 onkeydown="fnckeystop(event)" onpaste="return false" oncontextmenu="return false;"