一些常用的正则表达式:
匹配中文字符的正则表达式: [\u4e00-\u9fa5]
匹配HTML标记的正则表达式:<(\S*?)[^>]>.?|<.*? />
匹配邮箱地址的正则表达式:[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^ [a-zA-Z][a-zA-Z0-9_]{4,15}
匹配国内电话号码:\d{3}-\d{8}|\d{4}-\d{7}
匹配腾讯QQ号:[1-9][0-9]{4,10}
匹配中国邮政编码:[1-9]\d{5}(?!\d)
匹配身份证:([1-9][0-9]{14})|([1-9][0-9]{16}[0-9xX])
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body {
background: #ccc;
}
label {
width: 40px;
display: inline-block;
}
span {
color: red;
}
.container {
margin: 100px auto;
width: 400px;
padding: 50px;
line-height: 40px;
border: 1px solid #999;
background: #efefef;
}
span {
margin-left: 30px;
font-size: 12px;
}
.wrong {
color: red
}
.right {
color: green;
}
.defau {
width: 200px;
height: 20px;
}
.de1 {
background-position: 0 -20px;
}
</style>
</head>
<body>
<div class="container" id="dv">
<label for="qq">Q Q</label><input type="text" id="qq"><span></span><br/>
<label>手机</label><input type="text" id="phone"><span></span><br/>
<label>邮箱</label><input type="text" id="e-mail"><span></span><br/>
<label>座机</label><input type="text" id="telephone"><span></span><br/>
<label>姓名</label><input type="text" id="fullName"><span></span><br/>
</div>
<script src="commo.js"></script>
<script>
//qq的
checkInput(my$("qq"),/^\d{5,11}$/);
//手机
checkInput(my$("phone"),/^\d{11}$/);
//邮箱
checkInput(my$("e-mail"),/^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/);
//座机号码
checkInput(my$("telephone"),/^\d{3,4}[-]\d{7,8}$/);
//中文名字
checkInput(my$("fullName"),/^[\u4e00-\u9fa5]{2,6}$/);
//通过正则表达式验证当前的文本框是否匹配并显示结果
function checkInput(input,reg){
//文本框注册失去焦点事件
input.onblur=function(){
if(reg.test(this.value)){
this.nextElementSibling.innerText="正确了";
this.nextElementSibling.style.color="green";
}else{
this.nextElementSibling.innerText="错了";
this.nextElementSibling.style.color="red";
}
}
}
</script>
</body>
</html>
显示结果