利用js实现表单验证
?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表单验证</title>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid black;
margin: 0 auto;
line-height: 50px;
box-sizing: border-box;
}
span{
color: red;
}
</style>
</head>
<body class="box">
用户名:<input type="text" id="user"><span></span><br>
密码:<input type="text" id="password"><span></span><br>
确认密码:<input type="text" id="password2"><span></span><br>
手机号:<input type="text" id="tel"><span></span><br>
邮箱:<input type="text" id="email"><span></span><br>
<input type="button" id="btn" value="提交">
</body>
<script>
// 1.用户名 用户名仅支持中文、字母、数字、“-”“_”的组合,4-20个字符
// 2.密码的规则 数字字母特殊字符,一种类型,弱。两种类型为中,三种类型为强
// 3.重复密码 跟第一次输入 密码一致
// 4.手机号的验证 第一位必须为1,后面再加10位数字
// 5.邮箱 数字大小写字母_- 3到12位 @ 数字字母 2到9位 . 字母2到5位
// 6.提交按钮的时候,判断所有输入数据是否符合。符合跳转,否,不跳
var ous = document.getElementById("user");
var opd = document.getElementById("password");
var opd2 = document.getElementById("password2");
var otel = document.getElementById("tel");
var oem = document.getElementById("email");
var obtn = document.getElementById("btn");
//用户名
ous.onblur = function(){
var span = this.nextElementSibling;
if(/^[\u2E80-\u9FFF\w\-]{4,20}$/.test(this.value)){
span.innerHTML = "ok";
this.style.border="2px solid green";
us = true;
}else{
span.innerHTML = "no";
this.style.border="2px solid red";
us = true;
}
}
// 密码
opd.onblur = function(){
var span = this.nextElementSibling;
var a = /\d/.test(this.value)? 1:0;
var b = /[a-z]/i.test(this.value)? 1:0;
var c = /[^a-z\d]/i.test(this.value)? 1:0;
switch(a+b+c){
case 1:span.innerHTML = "弱";break;
case 2:span.innerHTML = "中";break;
case 3:span.innerHTML = "强";break;
this.style.border="2px solid green";
}
pd = true;
}
// 确认密码
opd2.onblur = function(){
var span = this.nextElementSibling;
if(this.value === opd.value){
span.innerHTML = "一致"
this.style.border="2px solid green";
pd2 = true;
}else{
span.innerHTML = "两次密码不一致"
pd2 = false;
this.style.border="2px solid red";
}
}
otel.onblur = function(){
var span = this.nextElementSibling;
if(/^1[3-9]\d{9}$/.test(this.value)){
span.innerHTML = "通过验证";
this.style.border="2px solid green";
tel = true;
}else{
span.innerHTML = "不符合手机号的基本格式";
this.style.border="2px solid red";
tel = true;
}
}
// 邮箱
var oemail = document.getElementById("email");
oem.onblur = function(){
// var reg5 = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;
var span = this.nextElementSibling;
if(/^[\w-]{2,10}@[\da-z]{2,10}\.[a-z]{2,4}$/.test(this.value)){
span.innerHTML = "ok";
em = true;
}else{
span.innerHTML = "no";
em = false;
}
}
obtn.onclick = function(){
if(us && pd && pd2 && tel && em ){
alert("成功")
}else{
alert("失败")
}
}
</script>
</html>
|