<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
QQ号:<input type="text" id="txtQQ"><span></span><br>
邮箱:<input type="text" id="txtEMail"><span></span><br>
手机:<input type="text" id="txtPhone"><span></span><br>
生日:<input type="text" id="txtBirthday"><span></span><br>
姓名:<input type="text" id="txtName"><span></span><br>
<script>
//获取文本框
var txtQQ = document.getElementById("txtQQ");
var txtEMail = document.getElementById("txtEMail");
var txtPhone = document.getElementById("txtPhone");
var txtBirthday = document.getElementById("txtBirthday");
var txtName = document.getElementById("txtName");
//正则表达式
var regQQ = /^\d{5,12}$/;
var regMail = /^\w+@\w+\.\w+(\.\w+)?$/;
var regPhone = /^\d{11}$/;
var regBirthday = /^\d{4}-\d{1,2}-\d{1,2}$/;
var regName = /^[\u4e00-\u9fa5]{2,4}$/;
//添加验证
addCheck(txtBirthday, regBirthday, "请输入正确的出生日期");
addCheck(txtEMail, regMail, "请输入正确的邮箱地址");
addCheck(txtPhone, regPhone, "请输入正确的手机号码");
addCheck(txtName, regName, "请输入正确的姓名");
addCheck(txtQQ, regQQ, "请输入正确的QQ");
//给文本框添加验证
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 = "";
}
};
}
</script>
</body>
</html>
正则表达表单验证判断qq,邮箱,手机号
最新推荐文章于 2024-06-18 19:54:54 发布