JavaScript实现表单校验的代码和思路分析
思路分析
- 写个checkName函数,用正则校验用户名,返回校验结果,结果要么为fasle,要么为true
- 给用户名输入框绑定失去焦点的onblur事件,事件中调用已定义好的checkName函数
- 给表单form绑定onsubmit事件,事件中直接调用并返回checkName函数的结果,由结果来决定是否提交表单’
代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<style>
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body{
background: url("../img/register_bg.png") no-repeat center;
padding-top: 25px;
}
.rg_layout{
width: 900px;
height: 500px;
border: 8px solid #EEEEEE;
background-color: white;
margin: auto;
}
.rg_left{
float: left;
margin: 15px;
}
.rg_left > p:first-child{
color:#FFD026;
font-size: 20px;
}
.rg_left > p:last-child{
color:#A6A6A6;
font-size: 20px;
}
.rg_center{
float: left;
}
.rg_right{
float: right;
margin: 15px;
}
.rg_right > p:first-child{
font-size: 15px;
}
.rg_right p a {
color:pink;
}
.td_left{
width: 100px;
text-align: right;
height: 45px;
}
.td_right{
padding-left: 50px ;
}
#username,#password,#email,#name,#tel,#birthday,#checkcode{
width: 251px;
height: 32px;
border: 1px solid #A6A6A6 ;
border-radius: 5px;
padding-left: 10px;
}
#checkcode{
width: 110px;
}
#img_check{
height: 32px;
vertical-align: middle;
}
#btn_sub{
width: 150px;
height: 40px;
background-color: #FFD026;
border: 1px solid #FFD026 ;
}
#sub_btn {
padding-left: 150px;
}
.error{
color: red;
}
</style>
<script>
window.onload = function () {
document.getElementById("form").onsubmit = function () {
return checkPassword() && checkUsername() && checkEmail() && checkName() && checkTel() && checkCode();
}
document.getElementById(