<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<form action="#" method="post">
<label>QQ号:</label><input type="text" id="txtQQ"><span></span><br>
<label>邮箱:</label><input type="text" id="txtEmail"><span></span><br>
<label>手机:</label><input type="text" id="txtPhone" οnblur="checkPhone()"><span id="msgPhone"></span><br>
<input type="submit" value="提交" id="btn"/>
</form>
</body>
</html>
* {
margin: 0;
padding: 0;
}
form{
width: 800px;
height: 200px;
margin: 200px auto;
}
label{
display: inline-block;
width: 60px;
text-align: right;
margin-left: 200px;
}
#btn{
margin: 20px 330px;
}
span{
width: 200px;
}
window.onload = function() {
//获取文本框
var txtQQ = document.getElementById("txtQQ");
var txtEmail = document.getElementById("txtEmail");
//
txtQQ.onblur = function() {
//获取当前文本框对应的 span
var span = this.nextElementSibling;
var reg = /^\d{5,12}$/;
//判断验证是否成功
if (!reg.test(this.value)) {
//验证不成功
span.innerText = " *请输入正确的 QQ 号";
span.style.color = "red";
} else {
//验证成功
span.innerText = " *验证通过";
span.style.color = "green";
}
};
//邮箱验证部分,封装成函数:
var regEmial = /^\w+@\w+\.\w+(\.\w+)?$/;
//调用函数 ia
addCheck(txtEmail, regEmial, " *请输入正确的邮箱地址");
//给文本框添加验证
function addCheck(element, reg, tip) {
element.onblur = function() {
//获取当前文本框对应的 span
var span = this.nextElementSibling;
//判断验证是否成功
if (!reg.test(this.value)) {
//验证不成功
span.innerText = tip;
span.style.color = "red";
} else {
//验证成功
span.innerText = " *验证通过";
span.style.color = "green";
}
};
}
}
function checkPhone() {
var txtPhone = document.getElementById("txtPhone");
var msgPhone = document.getElementById("msgPhone");
var reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
//判断验证是否成功
if (!reg.test(txtPhone.value)) {
//验证不成功
msgPhone.innerText = " *请输入正确的手机号";
msgPhone.style.color = "red";
} else {
//验证成功
msgPhone.innerText = " *验证通过";
msgPhone.style.color = "green";
}
}