表单验证
```
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
//表单验证
function checkform()
{
//1. 校验用户名 5位以上字母
//2. 校验密码 6位以上字母
//3. 确认密码和密码一样
if(checkusername() && checkpassword() && checkpassword2())
{
return true;
}
alert("请修改信息再提交");
return false;
}
function checkusername()
{
var username = document.getElementById("username").value;
if(username.length<=5)
{
document.getElementById("usernamemsg").innerHTML = "x";
return false;
}
else
{
document.getElementById("usernamemsg").innerHTML = "√";
return true;
}
}
function checkpassword()
{
var pwd = document.getElementById("pwd").value;
if(pwd.length<=6)
{
document.getElementById("pwdmsg").innerHTML = "x";
return false;
}
else
{
document.getElementById("pwdmsg").innerHTML = "√";
return true;
}
}
function checkpassword2()
{
var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd==pwd2)
{
document.getElementById("pwd2msg").innerHTML = "√";
return true;
}
else
{
document.getElementById("pwd2msg").innerHTML = "x";
return false;
}
}
</script>
<form action="http://www.baidu.com" method="post" onsubmit="return checkform()">
<input name="username" id="username" type="text" placeholder="用户名" onblur="checkusername()"/><span id="usernamemsg"></span><br/>
<input name="pwd" id="pwd" type="password" placeholder="密码" onblur="checkpassword()"/><span id="pwdmsg"></span><br/>
<input name="pwd2" id="pwd2" type="password" placeholder="确认密码" onblur="checkpassword2()"/><span id="pwd2msg"></span><br/>
<input name="email" id="email" type="email" placeholder="邮箱"/>
<button type="submit">提交</button>
</form>
</body>
</html>
~~~
```
正则表达式:
```
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" onblur="checkvalue(this)"/>
<input type="text" onblur="checkusername(this)"/>
<script>
//正则表达式,不是js特有的,各个语言对于语法支持上略有区别
function checkvalue(ctrl)
{
//1. 校验一下邮政编码
var reg = /^\d{6}$/;
//2. 邮政编码
var postcode = ctrl.value;
//3. 校验
if(reg.test(postcode))
{
console.log("符合");
}
else
{
console.log("不符合");
}
}
//2. 校验6位以上字母数字下划线
// /^\w{6,}$/
//3. 校验身份证号码(18位),其中最后一位可能X
// /^\d{17}[0-9X]$/
//4. 邮箱校验
// /^\w+@\w+(\.\w{2,3}){1,2}$/
//5. 校验密码的安全性,6位以上,字母数字,下划线,大写字母
// /^ \w{6,} $/
function checkusername(ctrl)
{
var str = ctrl.value;
var reg = /^\w{6,}$/;
if(!reg.test(str))
{
alert("不符合");
return;
}
//判断是否包含大写字母
var isFound = false;
for(var i=0; i<str.length;i++)
{
if(str.charAt(i)>="A" && str.charAt(i)<="Z")
{
//包含大写字母了
isFound = true;
break;
}
}
if(!isFound)
{
alert("不符合");
return;
}
alert("符合");
}
</script>
</body>
</html>
~~~
```