常见且简单的正则验证表达式--更新中
<script>
function check(){
//通过循环判断表单项是否为空
for(i=0;i<=7;i++){
var e=document.forms[0].elements[i];
if(e.value==""){
alert("不能为空!");
e.focus();
return false;
}
}
}
function css(num,zw){ //num:处理的表单元件索引
zw:0错误 1正确
if(zw==1){
document.forms[0].elements[num].style.border="1px green solid"
document.getElementById("mv"+num).innerHTML="<font color=green>* 正确</font>";
}
else if(zw==0){
document.forms[0].elements[num].style.border="1px red solid"
document.getElementById("mv"+num).innerHTML="<font color=red>* 错误!</font>";
}
}
</script>
<form name="form1" method="post" action="b.asp">
<label> 姓名:
<input name="xm" id="xm" onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))">
</label>
<span id="mv0">*只能输入中文</span>
<p>
<label>
用户名:
<input onkeyup="value=value.replace(/[\W]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
</label>
<span id="mv1">*只能输入英文和数字</span></p>
<p>
<label>密码:
<input type="text" name="pass" onchange="if(!(/^(\w){6,20}$/).test(this.value)){css(2,0)}else{css(2,1)}">
</label>
<span id="mv2">*只能输入6-20个字母、数字、下划线</span></p>
<p>身份证号:
<label>
<input onchange="if(!(/^\d{17}(?:\d|x)$/).test(this.value)){css(3,0)}else{css(3,1)}">
</label>
<span id="mv3">*18位身份证</span></p>
<p>电话:
<label>
<input type="text" onchange="if(!(/^[+]{0,1}(\d){1,3}[ ]?([-]?(\d){1,12})+$/).test(this.value)){css(4,0)}else{css(4,1)}">
</label>
<span id="mv4">*可以“+”开头,除数字外,可含有“-”</span></p>
<p>手机:
<label>
<input onchange="if(!(/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/).test(this.value)){css(5,0)}else{css(5,1)}">
</label>
<span id="mv5">*必须以数字开头,除数字外,可含有“-”</span></p>
<p>
<label>邮编:
<input onchange="if(!(/^\d{6}$/).test(this.value)){css(6,0)}else{css(6,1)}">
</label>
<span id="mv6">*6位数字</span></p>
<p>email:
<label>
<input onchange="if(!(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/).test(this.value)){css(7,0)}else{css(7,1)}">
</label>
<span id="mv7">*email</span></p>
<p>
<label>
<input type="button" value="提交" onClick="check()">
</label>
</p>
<p> </p>
<p><br>
用正则表达式限制只能输入中文:<br>
<input onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))">
<br>
用正则表达式限制只能输入全角字符: <br>
<input onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))">
<br>
用正则表达式限制只能输入数字:<br>
<input onkeyup="value=value.replace(/[^\d]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
<br>
用正则表达式限制只能输入数字和英文:<br>
<input onkeyup="value=value.replace(/[\W]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
</p>
</form>